Laravel Eloquent。我试着将两个中间表相交. 有没有比这个更有效的查询方法?

问题描述 投票:1回答:1

Laravel Eloquent.I try to intersect two intermediate table. 我试着与两个中间表相交, 有没有比这个更有效的查询? 还有什么查询比这个更有效的吗?

单位模型 :

public function products()
{
    return $this->belongsToMany('App\Product');
}

public function users()
{
    return $this->belongsToMany('App\User');
}

产品模型 :

public function units()
{
    return $this->belongsToMany('App\Unit');
}

public function users()
{
    return $this->belongsToMany('App\User');
}

用户模型:

public function units()
{
    return $this->belongsToMany('App\Unit');
}

public function products()
{
    return $this->belongsToMany('App\Product');
}

查询口才。

Product::get()

->filter(function ($product) {
    return $product->units
                    ->pluck('id')
                    ->intersect(auth()->user()->units->pluck('id'))
                    ->isNotEmpty();
})

我试图检索所有产品,其中产品单位等于用户登录单位。


更新

我觉得下面的代码更简洁

Product::whereHas('units', function (Builder $query) {
    $query->where([
        'units.id' => auth()->user()->units->pluck('id'),
    ]);
})->get();
php laravel eloquent
1个回答
0
投票

我认为你的解决方案看起来是最佳的!这看起来像是一种比较属性的方法。它看起来就像一个比较两个数据透视表属性的方法,其方式为

Product::with('users')
        ->with('units')
        ->compareAttributesFromPivotTables('attribute_a','attribute_b')
        ->get();

还没有实施。

© www.soinside.com 2019 - 2024. All rights reserved.