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

foo*_*.ar 5 php 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');
   }

}
Run Code Online (Sandbox Code Playgroud)

有没有比使用DB::raw()手动连接、分组和计数的查询更雄辩(双关语)的方法来解决这个问题?

Ken*_*rna 0

在数据库级别我不知道如何实现这一点,但您可以在集合级别做到这一点。

// Get users
$agents = Agent::withCount('tickets')->get();
// filter
$good_agents = $agents->filter(function ($agent, $key) {
                   return $agent->tickets_count >= $agent->quota;
               })
               ->all();
Run Code Online (Sandbox Code Playgroud)

当然你可以内联它:

$good_agents = Agent
    ::withCount('tickets')
    ->get()
    ->filter(function ($agent, $key) {
        return $agent->tickets_count >= $agent->quota;
    })
    ->all();
Run Code Online (Sandbox Code Playgroud)