Querying child objects that satisfy condition on parent objects, Relationship with eloquent laravel

-3

I have two tables in my project that relate, but I would like to make a query consult that would bring all the child entities that one field would be equal to the parent entity, being for all parent entities that satisfy a specific condition.

Could someone help me?

I want to take all the wheels that vehicle (parent class) is red, with vehicles being a table, wheels is another, and color (red) is a field. Fictitious example. In this case I want all the wheels only.

    
asked by anonymous 17.10.2017 / 13:01

1 answer

3

Since you did not give a real example, I used the dummy classes Pai and Filho

$dados = Pai::with('filhos')->where('coluna', 'algum valor')->get();

In this case, you must have the mapped relation in the model

class Pai extends Model
{
    public function filhos() {
        return $this->hasMany(Filho::class);
    }
}

Applying to the example of Veiculo and Roda

class Veiculo extends Model 
{
    public function rodas() {
        return $this->hasMany(Roda::class);
    }
}

The use would be

$dados = Veiculo::with('rodas')->where('cor', 'vermelho')->get();

To return only the child entities, you can do a join

$dados = Roda::join('veiculos', function($query) {
    $query->on('veiculos.id', '=', 'rodas.veiculo_id');
    $query->where('veiculo.cor', '=', 'vermelho');
})
->get();
17.10.2017 / 13:10