Laravel HasManyThrough with 3 路数据透视表


Laravel HasManyThrough with 3-way pivot table

我有以下型号

食谱

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

成分

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

单位

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

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

成分食谱单位

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` = ?

而实际上查询应如下所示。(注意第 3 行id -> recipe_id 的细微变化(

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

除了向 Eloquent 存储库发送拉取请求以添加额外的参数或使用原始 SQL; 有没有办法解决这个问题?

最终是我想出关系方式上的一个错误,它通过简单地定义从各个相关模型直接到IngredientRecipeUnit表的belongsToMany来解决。

例如:成分模型

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

根据您的型号,您可能有可能添加相同成分或单位的多个,在这种情况下,您应该使用 instinct方法标记查询。

喜欢这个:

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

哪个相关生成以下所需查询:

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