2016-05-09 106 views
1

我有以下型号Laravel HasManyThrough与3路透视表

配方

public function ingredientRecipeUnits() 
{ 
    return $this->hasMany(IngredientRecipeUnit::class); 
} 

成分

public function ingredientRecipeUnits() 
{ 
    return $this->hasMany(IngredientRecipeUnit::class); 
} 

单位

public function ingredientRecipeUnits() 
{ 
    return $this->hasMany(IngredientRecipeUnit::class); 
} 

和数据透视表(在其自己的模型)连接所有三个:

IngredientRecipeUnit

public function ingredient() 
{ 
    return $this->belongsTo(Ingredient::class); 
} 

public function recipe() 
{ 
    return $this->belongsTo(Recipe::class); 
} 

public function unit() 
{ 
    return $this->belongsTo(Unit::class); 
} 

我想通过配料模型来获取所有的食谱。

为此,我做了如下关系:

public function recipes() { 
    return $this->hasManyThrough(
     Recipe::class,  
     IngredientRecipeUnit::class, 
     'ingredient_id', 
     'id' 
    ); 
} 

这产生不正确查询看起来像这样

select * from `recipes` 
inner join `ingredient_recipe_units` 
on `ingredient_recipe_units`.`id` = `recipes`.`id` 
where `ingredient_recipe_units`.`ingredient_id` = ? 

而在现实的查询应该是这样的。 (注意的id微妙的变化 - 在第3行>recipe_id

select * from 'recipes' 
inner join `ingredient_recipe_units` 
on `ingredient_recipe_units`.`recipe_id` = `recipes`.`id` 
where `ingredient_recipe_units`.`ingredient_id` = ? 

除了发送拉请求到锋回购添加一个额外的参数或使用原始SQL;有什么办法可以解决这个问题吗?

回答

0

这最终是我考虑关系时的一个错误,它是通过简单地将各个相关模型的belongsToMany直接定义到IngredientRecipeUnit表解决的。

例如:配料模型

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

根据你的模型,你可能需要添加相同成分或单位的倍数,在这种情况下,你应该标记与本能方法查询的可能性。

像这样:

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

哪correclty生成以下所需的查询:

select distinct * from `recipes` 
inner join `ingredient_recipe_units` 
on `recipes`.`id` = `ingredient_recipe_units`.`recipe_id` 
where `ingredient_recipe_units`.`ingredient_id` = ?