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();
答案 0 :(得分:3)
这就是我们最终的工作原理。
重要补充:数据透视表是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,以便在您为父母时始终加载。
答案 1 :(得分:0)
您必须使用子查询来做到这一点:
public function oldestKid()
{
return $this->belongsTo(Kid::class);
}
public function scopeWithOldestKid($query)
{
$query->addSelect(['oldest_kid_id' => Kid::select('id')
->whereColumn('parent_id', 'parents.id')
-> orderByDesc('age')
->take(1)
])->with('oldestKid');
}
然后您可以像这样使用它:
$parents = Parent::withOldestKid()->get();
foreach($parents as $parent){
$oldest_kid = $parent->oldestKid;
}