A
A
axblue2017-02-16 01:43:59
Laravel
axblue, 2017-02-16 01:43:59

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

"Let's say there is a post with elements associated with this post. We can get all the posts by the element and, in turn, the elements by the post. (Many-to-many relationship.).
Actually, the question is how to make a selection and sorting .. Let's go to element1 and display all the elements with which it is most often used in posts."

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrzej Wielski, 2017-02-16
@wielski

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);
}

Flavor
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();
}

Conclusion:
$flavor = Flavor::find(1);
dd($flavor->mostPostable);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question