我有一个测试网站,我有recipes
,ingredients
和ingredient_uses
个表格。每个食谱"使用"不同数量的成分和不同的成分(例如切碎,切片,切碎,磨碎),因此ingredient_uses
表跟踪recipe_id
和ingredient_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
我应该使用更合适的关系吗?
答案 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