dimanche 3 juillet 2016

Cardinality violation error when using whereHas cause in Laravel

I have two tables named Users and Children.

I want to find all users have children with special age ranges.

There is no age field in children table and I must calculate it before select.

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

in Child model I wrote this scope:

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);
}

But it cause to this error:

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)



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire