Laravel Eloquent. I try to intersect two intermediate table. Is there any query more efficient than this?

谁都会走 提交于 2021-01-28 19:35:48

问题


Laravel Eloquent. I try to intersect two intermediate table. Is there any query more efficient than this ?

Unit Model :

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

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

Product Model :

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

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

User Model :

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

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

Query Eloquent :

Product::get()

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

I try to retrieve all product where product unit is equal user login unit


UPDATE

I think code below is more clean

Product::whereHas('units', function (Builder $query) {
    $query->where([
        'units.id' => auth()->user()->units->pluck('id'),
    ]);
})->get();

回答1:


I think your solutions looks optimal! It looks like a way to compare attributes from two pivot tables in the way

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

isn't yet implemented.



来源:https://stackoverflow.com/questions/61625336/laravel-eloquent-i-try-to-intersect-two-intermediate-table-is-there-any-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!