【问题标题】:Laravel: How to write a join count query on belongsToMany relationships?Laravel:如何编写关于 belongsToMany 关系的连接计数查询?
【发布时间】:2017-09-29 19:59:48
【问题描述】:

我得到了以下信息:

  • User、Role,带有一个 role_user 数据透视表和一个 belongsToMany 关系
  • 用户,位置,具有 location_user 数据透视表和 belongsToMany 关系

用户有 2 个角色:所有者和园丁

位置有一个“gardeners_max”字段

在模型位置:

protected $appends = ['is_full'];

public function getIsFullAttribute()
{
    return $this->attributes['name'] = $this->remainingGardeners() <= 0;
}

public function countGardeners() 
{
    return $this->gardeners()->count();
}

public function remainingGardeners() 
{
    return $this->gardeners_max - $this->countGardeners();
}

现在,这样做:

Location::all();

我明白了:

[
 {
   name: 'LocationA',
   gardeners_max: 3,
   owners: [...],
   garderners: [...]
   ...
   is_full: false
 }
]

这很酷。但是...不可能对附加属性执行 WHERE 子句。

Location::where('is_full',true)->get() // Unknown column 'is_full' in 'where clause'

所以我想写一个连接查询,这样我就可以在 is_full 上做一个 where 子句

我就是找不到路。任何帮助将不胜感激!

重要提示:

我知道获取结果的 filter() 方法,但我需要在这里执行一个 scopeQuery

【问题讨论】:

    标签: laravel eloquent query-builder


    【解决方案1】:

    您可以像这样在您的位置模型中设置范围

    public function scopeFull(Builder $query)
    {
        return $query->where('is_full', true);
    }
    

    现在您只需像这样获得所有位置

    Location::full()->get();
    

    【讨论】:

    • 谢谢,但它不会起作用,因为在 WHERE 子句中没有考虑附加属性......所以我想我需要一个连接查询
    【解决方案2】:

    您可以在从数据库加载对象后尝试操作Collection

    Location::get()->where('is_full', true)->all();
    

    (您必须先使用get,然后再使用all,否则不确定是否有效)

    不确定这是优化的想法。

    【讨论】:

    • 谢谢,但正如我刚刚编辑的那样,我真的需要做(并理解)如何编写连接查询
    猜你喜欢
    • 2021-10-07
    • 2018-05-19
    • 2015-02-22
    • 2019-05-08
    • 1970-01-01
    • 2018-03-08
    • 2021-03-22
    • 2021-10-17
    • 2019-07-08
    相关资源
    最近更新 更多