首页 > 解决方案 > 如何通过急切加载返回一个雄辩的多对多关系实例?

问题描述

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();

标签: phplaraveleloquent

解决方案


这就是我们最终得到的结果,以及它的工作原理。

重要补充:数据透视表是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所以如果你去找父母,它总是会被加载。


推荐阅读