Answer the question
In order to leave comments, you need to log in
How to convert sql to Query Builder in Laravel?
Good evening. Help to adapt for Laravel (Query Builder) this query:
$similar_flavors = DB::select('SELECT d.flavor_id, COUNT(d.recipe_id) AS count FROM flavor_recipe
INNER JOIN flavor_recipe d ON d.recipe_id = flavor_recipe.recipe_id
WHERE flavor_recipe.flavor_id = 1 AND d.flavor_id <> 1
GROUP BY d.flavor_id
ORDER BY count');
//структура таблиц
recipes(посты)
id
...
flavors(элементы)
id
...
пост_элемент(связующая)
id
recipe_id
flavor_id
Answer the question
In order to leave comments, you need to log in
I remember already describing to you the logic of such a selection. So be it, I'll write the finished code, otherwise there's no way :)
Receip
public function flavors(){
return $this->belongsToMany(\App\Flavor::class);
}
public function flavors(){
return $this->belongsToMany(\App\Receip::class);
}
public function getMostPostableAttribute(){
return $this->flavors()->select(\DB::raw('`flavor_receipe.flavor_id`, count(`flavor_recipe.recipe_id`) as count'))->groupBy('flavor_receipe.flavor_id')->orderBy('count')->get();
}
$flavor = Flavor::find(1);
dd($flavor->mostPostable);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question