如何在Laravel Eloquent中为同一个表执行子查询

时间:2015-02-14 18:18:47

标签: php mysql laravel-4 eloquent

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

我的表结构是:

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'

1 个答案:

答案 0 :(得分:2)

您可以在同一张桌子上添加一个Eloquent关系,并将其过滤到右侧catType

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

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

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