假设我们有一个 agents
带有 quota
的 table 列和与 tickets
的多对多关系.使用 Laravel Eloquent ORM,我如何才能只选择“门票”数量少于或等于“配额”的代理人?
必须避免预先加载对象。
class Agent extends Model {
public function tickets()
{
return $this->belongsToMany(Ticket::class, 'agent_tickets')->using(AgentTicket::class);
}
public function scopeQuotaReached($query)
{
// Does not work. withCount is an aggregate.
return $query->withCount('tickets')->where('tickets_count', '<=', 'quota');
// Does not work. Tries to compare against the string "quota".
return $query->has('tickets', '<=', 'quota');
}
}
有没有比使用 DB::raw()
更有说服力(双关语)的方法来解决这个问题?手动加入、分组和计数查询?
编辑
作品:
$query->withCount('tickets')->having('tickets_count', '<=', DB::raw('quota'))->get();
作品:
$query->withCount('tickets')->having('tickets_count', '<=', DB::raw('quota'))->exists();
休息:( throw )
$query->withCount('tickets')->having('tickets_count', '<=', DB::raw('quota'))->count();
相关
https://github.com/laravel/framework/issues/14492
问题已关闭,链接到 #9307,我已经在那里发布了。会跟进。
最佳答案
tickets_count
等派生列只能在 HAVING
子句中访问。
由于没有 havingColumn()
方法,您必须使用原始表达式:
$query->withCount('tickets')->having('tickets_count', '<=', DB::raw('quota'));
关于php - 如何在 Laravel Eloquent 中将相关计数与自己的列进行比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55670383/