mardi 10 septembre 2019

Laravel: Retrieve relational data

Commodity:

public function variations() {
    return $this->hasMany( CommodityVariation::class )->with( 'unit' );
}

Recipe:

public function commodity_variations() {
    return $this->belongsToMany( CommodityVariation::class, 'recipe_commodity_variations' )->with( 'commodity' )->withTimestamps();
}

CommodityVariation:

public function commodity() {
    return $this->belongsTo( Commodity::class )->with( 'variations', 'allergens' );
}

public function recipes() {
    return $this->belongsToMany( Recipe::class, 'recipe_commodity_variations' )->withTimestamps();
}

What I'm looking for: I would like to get all recipes that use/have this specific commodity, but I've to go through my commodity_variations to find the relation between recipe and commodity. This is because recipe is linked to commodity variations and commodity variations is linked to commodity.

So what I've build so far, is this, but it just returns 50 recipes regardleess of what commodity_id I enter. For instance if I write 100000 instead of $commodity->id this returns 50 aswell.

$recipe = $department->recipes()->with(["commodity_variations" => function($q) use ( $commodity ) {
    $q->where('commodity_variations.commodity_id', '=', $commodity->id);
}])->get();

I really can't figure out what I'm doing wrong. I might be misunderstanding some basic stuff on how these relations work.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire