如何在 Laravel Eloquent 中对相同的 Table 进行子查询
How to do Subquery for same Table in Laravel Eloquent
我构建了一个类别 table 来存储类别和子类别。
我的table结构是:
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'
您可以在同一个 table 上添加 Eloquent 关系,并向右过滤 catType
:
public function children() {
return $this->hasMany('Model', 'parentID')->where('catType', 'Sub');
}
这使得项目的子项可用 $item->children
。你可以得到这样的计数:
$count = $item->children()->count();
我构建了一个类别 table 来存储类别和子类别。
我的table结构是:
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'
您可以在同一个 table 上添加 Eloquent 关系,并向右过滤 catType
:
public function children() {
return $this->hasMany('Model', 'parentID')->where('catType', 'Sub');
}
这使得项目的子项可用 $item->children
。你可以得到这样的计数:
$count = $item->children()->count();