1 回答
TA贡献1775条经验 获得超11个赞
所以我会假设这种关系是一个部门有很多员工。这是设置模型关系的方式。
<?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);
}
}
这是从数据库部分设置关系的方法(如果您没有正确拥有它)
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 关注
- 98 浏览
添加回答
举报