雄辩的计数嵌套关系 [英] Eloquent Count nested relationships

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

问题描述

| Data     | DataChildren   | Category
----------------------------------
|  id      | id             | id
|  name    | data_id        | name
|          | category_id    |
|          | name           |

数据模型:

public function data_children() {
   return $this->hasMany(DataChildren::class, 'data_id', 'id');
}

DataChildren模型:

DataChildren Model:

public function category() {
     return $this->belongsTo(Category::class, 'category_id', 'id');
}

我想通过 DataChildren 根据 Data id获取 Category 的数量.我只想从数据中获取类别记录,所以结果应该像这样

I want to get count of Category based on Data id through DataChildren. I just want to take the Category records from Data so the result should be like this

name from category | Count of category for Data
-------------------------------------------------
Unpublished        |   1
Published          |   3

我尝试使用此方法,但返回 null

I've tried using this but return null

Data::withCount(['category'=> function($query){return $query->groupBy('category_id');}])->find(1);

推荐答案

您需要使用在类别模型中:

 public function datas()
 {
        return $this->belongsToMany(Data::class, 'data_childerens', 'category_id', 'data_id');
 }

然后运行此查询 withCount :

Category::withCount('datas')->get();

设置数据模型:

public function categories()
{
     return $this->belongsToMany(Category::class, 'data_childerens', 'data_id', 'data_id');
}

然后运行此查询方式并 withCount :

Then run this Query With and withCount :

Data::with('categories')->withCount('datas')->get();

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

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