class Parent extends Model
{
public function kids()
{
return $this->belongsToMany('App\Models\Kid')
->orderBy('age')
->withTimestamps();
}
public function oldestKid()
{
return $this->belongsToMany('App\Models\Kid')
->orderByDesc('age')
->take(1);
}
}
这种方法的问题是 $parent->oldestKid
返回一个数组。如果它返回一个对象,感觉会更合乎逻辑。
$parent = App\Models\Parent::with('oldestKid')->first();
最佳答案
这就是我们最终得到的结果,以及它的工作原理。
重要补充:数据透视表是kid_parent
public function oldestKid()
{
return $this->belongsTo(Kid::class, 'oldest_kid_id', 'id');
}
public function scopeWithOldestKid($query)
{
$query->addSelect(['oldest_kid_id' => KidParent::select('kid_id')
->whereColumn('parent_id', 'parents.id')
->join('kids', 'kids.id', '=', 'kid_parent.kid_id')
->orderByDesc('kids.age')
->take(1)
])->with('oldestKid');
}
然后你就可以像那样使用它了:
$parents = Parent::withOldestKid()->get();
foreach($parents as $parent){
$oldest_kid = $parent->oldestKid;
}
如果你想发疯:你可以使用https://laravel.com/docs/8.x/eloquent#global-scopes所以如果你去找 parent ,它总是会被加载。
关于php - 如何通过预加载返回 Eloquent 多对多关系的一个实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64440891/