如何在Laravel Eloquent中将相关计数与自己的列进行比较?

假设我们有一个agents表,该表具有一quota列,并且与表具有多对多关系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();


休息时间:(投掷)

$query->withCount('tickets')->having('tickets_count', '<=', DB::raw('quota'))->count();




慕姐4208626
浏览 146回答 2
2回答

MMTTMM

像之类的派生列tickets_count只能在HAVING子句中访问。由于没有havingColumn()方法,因此必须使用原始表达式:$query->withCount('tickets')->having('tickets_count',&nbsp;'<=',&nbsp;DB::raw('quota'));

PIPIONE

在数据库级别,我不知道如何实现此目的,但是您可以在集合级别进行。// Get users$agents = Agent::withCount('tickets')->get();// filter$good_agents = $agents->filter(function ($agent, $key) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return $agent->tickets_count >= $agent->quota;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;})&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;->all();当然,您可以内联它:$good_agents = Agent&nbsp; &nbsp; ::withCount('tickets')&nbsp; &nbsp; ->get()&nbsp; &nbsp; ->filter(function ($agent, $key) {&nbsp; &nbsp; &nbsp; &nbsp; return $agent->tickets_count >= $agent->quota;&nbsp; &nbsp; })&nbsp; &nbsp; ->all();
打开App,查看更多内容
随时随地看视频慕课网APP