如何在选择中使用Belongs表

时间:2015-02-16 20:45:26

标签: eloquent laravel-5

在laravel5中,我属于

模型中的模型
 public function LeaveCategories()
{
    return $this->belongsTo('App\LeaveCategories','leave_category_id','id');
}

然后我在

的控制器中查询
$userInfo = Leave::select(DB::raw('count(leaves.leave_category_id) as category_used'),
        'LeaveCategories.id','LeaveCategories.category','LeaveCategories.category_num')
        ->where('Leaves.leave_date','>=', $first_day_this_year)
        ->where('Leaves.leave_date','<=', $last_day_this_year)
        ->where('Leaves.leave_status', 1)
        ->groupBy('Leaves.leave_category_id','LeaveCategories.category','LeaveCategories.category_num','LeaveCategories.id')
        ->get();

但是它显示的错误是未知列&#39; LeaveCategories.id&#39;在&#39;字段列表&#39;

1 个答案:

答案 0 :(得分:0)

您使用QueryBuilder,但belongsTo是ActiveRecord。使用:

$userInfo = Leave::with('LeaveCategories')->where('Leaves.leave_date','>=', $first_day_this_year)
        ->where('Leaves.leave_date','<=', $last_day_this_year)
        ->where('Leaves.leave_status', 1)
        ->groupBy('Leaves.leave_category_id','LeaveCategories.category','LeaveCategories.category_num','LeaveCategories.id')
        ->get([DB::raw('count(leaves.leave_category_id) as category_used'),
        'LeaveCategories.id','LeaveCategories.category','LeaveCategories.category_num']);