我正在使用Laravel雄辩的ORM,我在一段特殊的关系中遇到了一个小问题。假设我有下表:
Recipe:
id | ... | ingredient1 | ingredient2 | ingredient3 | ingredient4每个菜谱都有4种成分,我从外部来源获得这种特定格式的数据,这就是为什么我把配料作为列而不是普通的多对多关系的原因。
我可以将这些设置为4个一对多的关系,但我希望能够写$ingredient->usedInRecipes()->get()。
对于4个一对多的关系,我必须编写$ingredient->usedInRecipesAsIngredient1()->get()、.、$ingredient->usedInRecipesAsIngredient4()->get(),然后再将它们合并,这将导致4个查询。
如果您知道在查询数据库之前加入这些关系的好方法,或者如何使4对多的关系工作,请回答!
发布于 2014-01-18 10:11:49
我找到了一个在我所有用例中都有效的解决方案。
在配方模型中,我将4种成分定义为一对多的关系,并建立了两个辅助作用域函数。
class Recipe extends Eloquent {
public function ingredient1()
{ return $this->belongsTo('Ingredient', 'ingredient1'); }
public function ingredient2()
{ return $this->belongsTo('Ingredient', 'ingredient2'); }
public function ingredient3()
{ return $this->belongsTo('Ingredient', 'ingredient3'); }
public function ingredient4()
{ return $this->belongsTo('Ingredient', 'ingredient4'); }
public function scopeHasIngredient( $query, Ingredient $ingredient ) {
return $query-> where( 'ingredient1', '=', $ingredient->id )
->orWhere( 'ingredient2', '=', $ingredient->id )
->orWhere( 'ingredient3', '=', $ingredient->id )
->orWhere( 'ingredient4', '=', $ingredient->id );
}
public function scopeWithIngredients( $query ) {
return $query->with('ingredient1', 'ingredient2',
'ingredient3', 'ingredient4');
}
}
class Ingredient extends Eloquent {
public function ingredientForRecipes() {
return Recipe::hasIngredient( $this )->withIngredients();
}
}为了获得所有的配方,我现在可以调用$ingredient->ingredientForRecipes()->get()并使用这些成分而不需要额外的查询。
发布于 2014-01-18 08:08:49
从这个问题上,我不知道你是否已经尝试过这一点,尽管在我看来,你只需要使用一个多到多的关系。
每个成分可能都有一组共同的属性,这些属性都可以在一个表ingredients中处理。
id name created_at updated_at
1 Paprika 01/01/1970 00:00:00 01/01/1970 00:00:00
1 Rosemary 01/01/1970 00:00:00 01/01/1970 00:00:00
1 Basil 01/01/1970 00:00:00 01/01/1970 00:00:00
1 Oregano 01/01/1970 00:00:00 01/01/1970 00:00:00然后你的recipes表
id name created_at updated_at
1 Herb Soup 01/01/1970 00:00:00 01/01/1970 00:00:00要保存这些关系,需要一个枢轴表ingredient_recipe
id recipe_id ingredient_id
1 1 1
2 1 2
3 1 3
4 1 4现在,您只需要在您的Recipe和Ingredient模型上建立一个Ingredient关系。
您可以编写安全代码,以确保一个菜谱只与配料有4种关系(如果您愿意的话),但要保持简单:
Recipe::with('ingredients')->get();会把所有的食材和食谱一起取回。
无枢轴
如果将列ingredient_1、ingredient_2等保留在recipes表中,则可以将类似的内容添加到Recipe模型中。
public function scopeGetWithIngredients($query)
{
$query->leftJoin('ingredients i1', 'recipes.ingredient_1', '=', 'i1.id')
->leftJoin('ingredients i2', 'recipes.ingredient_2', '=', 'i2.id')
->leftJoin('ingredients i3', 'recipes.ingredient_3', '=', 'i3.id')
->leftJoin('ingredients i4', 'recipes.ingredient_4', '=', 'i4.id')
->select('recipes.name', 'i1.name AS ing_1', 'i2.name AS ing_2');
}然后,您就可以在您的模型中获得以下内容:
Recipe::getWithIngredients();https://stackoverflow.com/questions/21201537
复制相似问题