【发布时间】:2019-06-12 06:04:01
【问题描述】:
我有下一个架构:
nutrients
|id|label |type
|1 |Avocado |fats
|2 |Cooked shrimp|proteins
|3 |Raw oatmeal |carbohydrates
|4 |Chocolate |fats
recipes
|id|label
|1 |Something with Avocado
|2 |Something w Avocado, chocolate and raw oatmeal
nutrient_recipe
|nutrient_id|recipe_id
|1 |1
|1 |2
|3 |2
|4 |2
而且我只想获取具有特定营养类型的食谱。 例如:
- 我想要一份只有脂肪的食谱。
它应该返回Something with Avocado (id: 1)
- 我想要一个只有脂肪和碳水化合物的食谱。
它应该返回Something w Avocado, Chocolate and raw oatmeal (id: 2)
我怎样才能做到这一点?
我正在使用 Laravel,如果您能利用 Eloquent,那就太好了。
编辑:
感谢@GordonLinoff
我可以实现下一个代码:
App\Models\Recipe::whereHas('nutrients', function ($query) {
$query->havingRaw("sum(case when nutrients.type = 'fats' then 1 else 0 end) > 0")
->havingRaw("sum(case when nutrients.type not in ('fats') then 1 else 0 end) = 0")
->groupBy('recipes.id')
->select('recipes.id');
})
显然这段代码属于过滤搜索,所以我希望这可以帮助某人。
【问题讨论】:
标签: sql laravel join many-to-many relationship