Laravel eloquent get relation count

前端 未结 5 2021
温柔的废话
温柔的废话 2021-02-05 00:29

I use Laravel 5.3.

I have 2 tables :

Articles
---------
id
cat_id
title

And

Category
---------
id
parent_id
title
         


        
5条回答
  •  不知归路
    2021-02-05 01:11

    I am sure somebody is still going through this, I was able to solve it the following way, suppose I have an Agent model and a Schedule model, i.e. one agent may have many schedules:

    class Schedule extends Model {
      public function agent() {
        return $this->belongsTo(Agent::class, 'agent_id');
      }
    }
    
    class Agent extends Model {
      public function user(){
        return $this->belongsTo(User::class);
      }
    
      public function schedules(){
        return $this->hasMany(Schedule::class);
      }
    }
    

    Well some agents may not necessarily have schedules assigned, thus, I filtered those before calling the with() method, like this:

    $agents = Agents::whereIn(
        'id', 
        Schedule::distinct()->pluck('agent_id')
    )->with('schedules')->get();
    

    Hope this helps!.

提交回复
热议问题