Use has
and whereHas
methods for limiting results based on the relations:
$bienes = Bien::whereHas( 'movimientos', function($sQuery){
$sQuery->where('dependencia_id', '=', 1);
})->get();
It will load only Bien models that have related movimientos
matching where clause.
jarektkaczyk said:
Use
has
andwhereHas
methods for limiting results based on the relations:$bienes = Bien::whereHas( 'movimientos', function($sQuery){ $sQuery->where('dependencia_id', '=', 1); })->get();
It will load only Bien models that have related
movimientos
matching where clause.
When I use that I get following error:
SQLSTATE[21000]: Cardinality violation: 1241 Operand should contain 19 column(s) (SQL: select * from `bien` where (select * from `movimiento` inner join `bien_movimiento` on `movimiento`.`id` = `bien_movimiento`.`movimiento_id` where `bien_movimiento`.`bien_id` = `bien`.`id` and `dependencia_id` = 1) >= 1)
So, I change a little bit your answer:
$bienes = Bien::whereHas('movimientos', function($sQuery){
// numero_lote is a colunm from movimiento table
$sQuery->where('dependencia_id', 1)->get(['numero_lote']);
})->get();
But, now I'm getting this error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'bien.id' in 'where clause' (SQL: select `numero_lote` from `movimiento` inner join `bien_movimiento` on `movimiento`.`id` = `bien_movimiento`.`movimiento_id` where `bien_movimiento`.`bien_id` = `bien`.`id` and `dependencia_id` = 1)
Like if the builder want to execute first the $sQuery and then the other side of the query...
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community