search

Home  >  Q&A  >  body text

One-to-many problem in laravel

I now have two tables:

One is the association list (list) and the user table (user)

List table fields

list_id(协会id) , list_name(协会名称)

user user table

user_id(用户id),list_id(所属协会), username(用户名)

How to achieve this:

Related query to obtain the total number of members under each association

For example:

{"list_name":"AAA协会","user_count":20},
{"list_name":"BBB协会","user_count":211}
...

How to connect?

高洛峰高洛峰2748 days ago246

reply all(1)I'll reply

  • 大家讲道理

    大家讲道理2017-05-16 16:50:52

    class List extends Model
    {
        protected $fillable = ['name'];
    
        public function users()
        {
            return $this->hasMany(User::class, 'list_id', 'id');
        }
    }
    
    class User extends Model
    {
        protected $fillable = ['list_id'];
    
        public function list()
        {
            return $this->belongsTo(List::class, "list_id", "id");
        }
    }
    
    List::withCount("users")->paginate();

    Read more documentation.

    reply
    0
  • Cancelreply