Laravel雄辩.我尝试相交两个中间表.有没有比这更有效的查询了? [英] Laravel Eloquent. I try to intersect two intermediate table. Is there any query more efficient than this?

查看:41
本文介绍了Laravel雄辩.我尝试相交两个中间表.有没有比这更有效的查询了?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Laravel雄辩.我尝试相交两个中间表.有没有比这更有效的查询了?

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

单位模型:

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

我尝试检索所有产品单位等于用户登录单位的产品

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

我认为下面的代码更干净

I think code below is more clean

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

推荐答案

我认为您的解决方案看起来是最佳的!看起来像是这样比较两个数据透视表中属性的一种方法

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

尚未实施.

这篇关于Laravel雄辩.我尝试相交两个中间表.有没有比这更有效的查询了?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆