我有三个名为users
,children
和children_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)