有三种模式。
class GrandParent extends Model
{
}
class Parent extends Model
{
public function children()
{
return $this->hasMany(Child::class);
}
public function grand_parent()
{
return $this->belongsTo(GrandParent::class);
}
}
class Child extends Model
{
protected $fillable = ['parent_id','grand_parent_id','data'];
}
将记录插入Child时,还会插入parent_id和grand_parent_id,但手动指定grand_parent_id
$data = $this->someDataGenerator();
$child = Child::first();
$child()->create([
'grand_parent_id' => $parent->grand_parent->id, //manually insert
'data' => $data
]);
有没有一种方法可以做到?因此,只要$child()->create($data)
, grand_parent_id 会自动插入?
答案 0 :(得分:0)
您无需向子表添加grand_parent_id
。
如果需要获得GrandParent的GrandParent:
$child = Child::find(1);
$grand_parent = $child->parent->grand_parent;
并使用“具有多次通过”关系从GrandParent模型中获取所有孩子:
class GrandParent extends Model
{
/**
* Get all of the grandchildren for the GrandParent.
*/
public function grandchildren()
{
return $this->hasManyThrough('App\Child', 'App\Parent');
}
}