laravel关系倒退

时间:2016-10-17 02:36:21

标签: php laravel relationship

我有一个测试网站,我有recipesingredientsingredient_uses个表格。每个食谱"使用"不同数量的成分和不同的成分(例如切碎,切片,切碎,磨碎),因此ingredient_uses表跟踪recipe_idingredient_id与其他变量信息。

关系看起来像这样:

食谱模型:

public function ingredients()
{
    return $this->hasManyThrough('App\Ingredient', 'App\IngredientUse');
}

public function ingredientUses()
{
    return $this->hasMany('App\IngredientUse');
}

Ingredient_Use模型:

public function ingredient()
{
    return $this->hasOne('App\Ingredient');
}

public function recipe()
{
    return $this->belongsTo('App\Recipe');
}

成分模型:

public function recipe()
{
    return $this->belongsToMany('App\Ingredient');
}

我以为我想要从配方到配料表的hasManyThrough关系,使用ingredient_uses作为中间表。但是sql错了:

SELECT `ingredients`.*, `ingredient_uses`.`recipe_id` 
FROM `ingredients`
INNER JOIN `ingredient_uses`
    ON `ingredient_uses`.`id` = `ingredients`.`ingredient_use_id` 
WHERE `ingredient_uses`.`recipe_id` = 1

这就是我想要的:

SELECT `ingredients`.*, `ingredient_uses`.`recipe_id`
FROM `ingredients` 
INNER JOIN `ingredient_uses`
    ON `ingredient_uses`.`ingredient_id` = `ingredients`.`id` 
WHERE `ingredient_uses`.`recipe_id` = 1

我应该使用更合适的关系吗?

2 个答案:

答案 0 :(得分:2)

首先 - 你不需要Ingredient_Use模型。模型示例:

class Ingredient extends Model
{
    /**
     * @var string
     */
    protected $table = 'ingredients';

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function recipes()
    {
        return $this->belongsToMany(Recipe::class, 'recipes_ingredients', 'ingredient_id');
    }
}




class Recipe extends Model
{
    /**
     * @var string
     */
    protected $table = 'recipes';

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function ingredients()
    {
        return $this->belongsToMany(Ingredient::class, 'recipes_ingredients', 'recipe_id')->withPivot('additional', 'fields');
    }
}

访问其他字段示例

$recipe->pivot->additional;

答案 1 :(得分:0)

成分模型

中的

class Ingredient extends Model
{


    public function recipe(){

          return $this->belongsToMany(Recipe::class, 'ingredient_uses', 'ingredient_id', 'recipe_id');
    }

}

其他模型将为空,这意味着配方模型和成分模型中不会有任何功能。

你可以看到关于这个的文档  https://laravel.com/docs/5.3/eloquent-relationships#many-to-many