Laravel - 显示Collection中的项目及其相关表中的总和

时间:2015-07-29 06:46:31

标签: php mysql laravel collections laravel-5

我在整理这个问题时遇到了问题。

我有两张桌子:

Users
+---------+
| id name |
+---------+
| 1 John  |
| 2 Ann   |
| 3 Joe   |
+---------+

Products
+---------------------+
| id product users_id |
+---------------------+
| 1  Bread      1     |
| 2  Apple      1     |
| 3  Egg        2     |
| 4  Juice      3     |
| 5  Cheese     3     |
| 6  Carrot     3     |
+---------------------+

我想创建一个查询,显示用户和products表中引用他的文章数。像这样:

+----------------------+
| name sum_of_products |
+----------------------+
| Ivan       2         |
| Ann        1         |
| Joe        3         |
+----------------------+

我有工作模式和关系。 我只能为这样的用户做一个查询

$sum = User::whereId(1)->products()->count();

但如何在一个查询中选择所有用户并获取所有计数?

3 个答案:

答案 0 :(得分:3)

laravels访问器功能怎么样?

您的用户模型应如下所示:

namespace App;

class User extends Model
{

    protected $appends = array('sum_of_products');

    public function getSumOfProductsAttribute() {

        return $this->products()->count();
    }
}

查看docu

答案 1 :(得分:1)

您可以通过以下方式获得所需:

$users = User::leftJoin('products', 'users.id', '=', 'products.user_id')->select('user_id', 'user.name')->selectRaw('count(*) as cnt')->groupBy('products.user_id')->get();

然后您可以像这样访问计数和用户:

foreach($users as $user) {
  $username = $user->name;
  $productCount = $user->cnt;
  ...; //do whatever you need with that data
}

答案 2 :(得分:0)

这是普通Cannot complete the install because one or more required items could not be found. Software being installed: m2e - Maven Integration for Eclipse (includes Incubating components) 1.6.1.20150625-2338 (org.eclipse.m2e.feature.feature.group 1.6.1.20150625-2338) Missing requirement: Maven Integration for Eclipse 1.6.0.20150526-2032 (org.eclipse.m2e.core 1.6.0.20150526-2032) requires 'bundle com.google.guava [14.0.1,16.0.0)' but it could not be found Missing requirement: Maven Integration for Eclipse 1.6.1.20150625-2338 (org.eclipse.m2e.core 1.6.1.20150625-2338) requires 'bundle com.google.guava [14.0.1,16.0.0)' but it could not be found Cannot satisfy dependency: From: m2e Marketplace 1.6.1.20150625-2338 (org.eclipse.m2e.discovery 1.6.1.20150625-2338) To: bundle org.eclipse.m2e.core [1.6.0,1.7.0) Cannot satisfy dependency: From: m2e - Maven Integration for Eclipse (includes Incubating components) 1.6.1.20150625-2338 (org.eclipse.m2e.feature.feature.group 1.6.1.20150625-2338) To: org.eclipse.m2e.discovery [1.6.1.20150625-2338]

SQL

在laravel中尝试一下,看看它是如何工作的:

SELECT users.name, count( products.users_id ) as sum_of_products
FROM products LEFT JOIN users ON users.id=products.users_id 
GROUP BY products.users_id