Answer the question
In order to leave comments, you need to log in
How to optimize laravel query?
Hello, please help me transfer my request to Eloquent to the maximum.
At first the request was completely "raw", now it has been transformed a little, but it turned out not very beautiful.
#
$subscriptions = Subscription::where('user_id', \Auth::user()->id)->lists('entity_id')->toArray();
$views = View::where('user_id', \Auth::user()->id)->lists('post_id')->toArray();
if ($subscriptions) {
$entityIds = '(' . implode(', ', $subscriptions) . ')';
}
if ($views) {
$ids = '(' . implode(', ', $views) . ')';
}
$result = Entity::leftJoin('countries', 'countries.id', '=', 'entities.country_id')
->leftJoin('posts', function($join) use ($entityIds, $ids) {
if ($entityIds) {
$join->on('posts.entity_id', 'IN', \DB::raw($entityIds));
}
if ($ids) {
$join->on('posts.id', 'NOT IN', \DB::raw($ids));
}
})
->selectRaw('
entities.id,
entities.alias,
entities.type,
entities.name,
countries.iso_code_3 AS country,
count(posts.id) AS unwatched
')
->get()
->toArray();
LEFT JOIN (
SELECT ....
) as Q2
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question