【问题标题】:Eloquent Count nested relationshipsEloquent Count 嵌套关系
【发布时间】:2021-05-03 08:11:27
【问题描述】:
| 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 模型:

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

我想根据Data id 到DataChildren 获取Category 的计数。 我只想从数据中获取类别记录,所以结果应该是这样的

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

我试过用这个但是返回null

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

【问题讨论】:

  • 看起来您需要多对多关系?除了外键,DataChildren 中还有其他属性吗
  • 不,它不应该是多对多关系,而是一对多。是的,我还有另一个属性@MKhalidJunaid
  • 用你的第二种方法什么不起作用,你得到无效计数吗?
  • 我收到一个错误Call to a member function getRelationExistenceCountQuery() on null@MKhalidJunaid
  • 很抱歉我错过了return

标签: php laravel eloquent laravel-7 eloquent-relationship


【解决方案1】:

你需要使用many to many关系

在类别模型中:

 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 运行此查询:

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

【讨论】:

  • 我收到错误Call to a member function getRelationExistenceCountQuery() on null
  • 很抱歉我错过了return
  • 非常感谢它有效! :D。我看不到多对多模式,因为真实模型有很多属性 xD。再次,非常感谢!
  • 我想获取Data 的名称和计数。如何? withCount 只是为了得到号码,但我也需要得到 name
  • Data::withCount(['category'=> function($query){return $query->groupBy('category_id');}])->find(1); 。我试过这个但返回null
猜你喜欢
  • 2017-11-19
  • 2020-03-19
  • 1970-01-01
  • 2019-01-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-17
  • 2016-06-29
相关资源
最近更新 更多