Counting a many to many relationship?

独自空忆成欢 提交于 2020-06-01 08:28:50

问题


I have a many to many relationship between users and images.

User Model

public function image()
{
    return $this->belongsToMany('\App\Image');
}

Image Model

public function user()
{
    return $this->belongsToMany('\App\User');
}

Tables

users

id | name

images

id | url

image_user

id | image_id | user_id

When a user 'favourites' an image, it's stored in the pivot table.

id | image_id | user_id
 1      1          1
 2      2          1
 3      1          2

I need a count of each images favourites.

I try something like:

 Image::with('user')->find(1)->count();

But this counts the number of users, not the number of favourites.

Ideally I would like to return all of the image data along with a count of the user data - how can I do this?


回答1:


You can do this:

$image = Image::with('user')->find(1) // Get the image with user eager loading
$image->name; // Access any attribute
$image->users->count(); // Get the user count

You can even add a few lines in your Image model to create a "custom" attribute:

public function getFavoritesAttribute()
{
    return count($this->users);
}

And then use it like this:

$image->favourites;

There is a more detailed solution here: Laravel many to many loading related models with count



来源:https://stackoverflow.com/questions/30507849/counting-a-many-to-many-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!