W
W
WebDev2016-04-08 22:12:16
Laravel
WebDev, 2016-04-08 22:12:16

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

The whole problem is that initially I had a select in the join:
LEFT JOIN (
    SELECT ....
) as Q2

In general, I need to count the number of records from a related table.
How can I simplify what I got?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question