数多对多的关系? [英] Counting a many to many relationship?

查看:78
本文介绍了数多对多的关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我与用户和图像之间有很多关系.

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

用户模型

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

图片模型

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

表格

用户

id | name

图片

id | url

image_user

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.

我尝试类似的事情:

 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?

推荐答案

您可以执行以下操作:

$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

您甚至可以在Image模型中添加几行以创建自定义"属性:

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

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

然后像这样使用它:

$image->favourites;

这里有一个更详细的解决方案: Laravel多对多与计数相关的加载模型

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

这篇关于数多对多的关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆