G
G
Glory2022-02-11 13:51:18
Laravel
Glory, 2022-02-11 13:51:18

How to translate a simple nested query into Eloquent?

There is one simple mysql query. But I need to convert it to Eloquent. I've looked all over and can't find the right design. Here is the request itself:

select c1.name, c1.id, (
    select count(*)
    from categories as c2
    where c2.id = c1.id
    group by c2.id) as rating
from categories c1;


If you do it through query builde, everything is simple there. but I need Eloquent to pull related entities in nested arrays.

Answer the question

In order to leave comments, you need to log in

4 answer(s)
V
Vlad Tokarev, 2022-02-17
@besogonskiy

I wrote the code, but did not check whether it works, but the idea is this:

// Создаем связь, можно методом в модели, можно на лету, как в примере
Category::resolveRelationUsing('categoryForRating', fn($q) => $orderModel->belongsTo(Category::class, 'id', 'id'));
Category::
  withCount('categoryForRating as rating')
  ->get(['name', 'id', 'rating_count as rating']);

P
pLavrenov, 2022-02-11
@pLavrenov

withCount()

V
Vyacheslav Plisko, 2022-02-11
@AmdY

Your request looks like nonsense, perhaps there is an error in it and you need to join by parant_id if you are making a tree.
Whereas you were prompted withCount and relaying on yourself to prescribe

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question