使用祖父 ID 插入/创建雄辩的关系



有三种型号。

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会自动插入吗?

不需要将

grand_parent_id添加到 Child 表中。如果需要获得祖父母的祖父母:

$child = Child::find(1);
$grand_parent = $child->parent->grand_parent;

并使用"通过多个"关系从祖父模型获取所有子项:

class GrandParent extends Model
{
    /**
     * Get all of the grandchildren for the GrandParent.
     */
    public function grandchildren()
    {
        return $this->hasManyThrough('AppChild', 'AppParent');
    }
}

最新更新