在Laravel中使用whereHas时,基数违规错误

时间:2016-07-03 09:43:50

标签: php laravel-5

我有三个名为userschildrenchildren_access的表作为支点。

我想找到所有用户都有特殊年龄段的孩子。

age表中没有children字段,我必须在选择之前计算它。

$users = User::whereHas('children',function($query){
   $query->inRange([3,4]);
});

在Child模型中我写了这个范围:

public function scopeInRange($query,$range_array)
{
    $sub = $query->select(DB::raw('*, TIMESTAMPDIFF(YEAR,birthdate,CURDATE()) AS age'));
    return DB::table(DB::raw("({$sub->toSql()}) as sub"))
        ->mergeBindings($sub->getQuery())
        ->whereIn('age',$range_array);
}

但它会导致此错误:

SQLSTATE[21000]: Cardinality violation: 1241 Operand should contain 43 column(s) (SQL: select * from `users` where (select *, TIMESTAMPDIFF(YEAR,birthdate,CURDATE()) AS age from `children` inner join `children_access` on `children`.`id` = `children_access`.`child_id` where `children_access`.`user_id` = `users`.`id`) >= 1)

0 个答案:

没有答案