1 回答

TA貢獻1775條經(jīng)驗 獲得超11個贊
所以我會假設(shè)這種關(guān)系是一個部門有很多員工。這是設(shè)置模型關(guān)系的方式。
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Employee extends Model
{
public function department()
{
return $this->belongsTo(Department::class);
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Department extends Model
{
public function employees()
{
return $this->hasMany(Employee::class);
}
}
這是從數(shù)據(jù)庫部分設(shè)置關(guān)系的方法(如果您沒有正確擁有它)
public function up()
{
Schema::create('departments', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->timestamps();
});
}
public function up()
{
Schema::create('employees', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->bigInteger('department_id')->unsigned();
$table->foreign('department_id')
->references('id')->on('departments')
->onDelete('cascade');
$table->timestamps();
});
}
- 1 回答
- 0 關(guān)注
- 118 瀏覽
添加回答
舉報