Support the ongoing development of Laravel.io →
Database Eloquent
Last updated 2 years ago.
0

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.

Last updated 2 years ago.
0

jarektkaczyk said:

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.

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...

Last updated 2 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.