gpt4 book ai didi

php - 如何在 Laravel Eloquent 中对同一张表进行子查询

转载 作者:行者123 更新时间:2023-11-29 02:22:47 26 4
gpt4 key购买 nike

我构建了一个类别表来存储类别和子类别。

我的表结构是:

catID (int)
catType (varchar 4)
parentID (int)
catName (varchar 50)
sOrder (int)

如何使用 Eloquent 进行后续子查询。

SELECT c.*, 
(
SELECT COUNT(*) FROM categories AS sc WHERE sc.parentID = c.catID AND sc.catType = "Sub"
) AS totalSubCategories
FROM categories AS c
WHERE c.catType = 'Root'

我试过以下但它不会工作:

$rows = CategoryModel::from('categories as c')
->where('c.catType', '=', 'Root')
->paginate(20)
->select(DB::raw('c.*, (SELECT COUNT(*) FROM categories as sc WHERE sc.parentID = c.catID AND sc.catType = "Sub") AS totalCategories'));

我遇到以下错误

ErrorException (E_UNKNOWN) 
call_user_func_array() expects parameter 1 to be a valid callback, class 'Illuminate\Support\Collection' does not have a method 'select'

最佳答案

可以在同一张表上添加Eloquent关系,过滤到合适的catType:

public function children() {
return $this->hasMany('Model', 'parentID')->where('catType', 'Sub');
}

这使得该项目的子项可用作 $item->children。你可以像这样得到一个计数:

$count = $item->children()->count();

关于php - 如何在 Laravel Eloquent 中对同一张表进行子查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28518709/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com