问题
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