One-to-many problem in laravel
高洛峰
高洛峰 2017-05-16 16:48:52
0
1
245

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?

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(1)
大家讲道理
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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template