mardi 14 avril 2020

A scope performing very slowlly while it's SQL counterpart performs fast

This is my table structure:

messages

| id | user_id | subject | body | parent_id |

messages_user
| id | message_id | user_id |

In the model Message.php I have this scope:

public function scopeForMe($query)
{
    $userId = Auth::user()->id;
    return $query->whereRaw('(id in (select coalesce(parent_id, message_id) from message_user mu join messages m on (mu.message_id = m.id) where mu.user_id = ?) or user_id = ?)', [$userId, $userId]);
}

when I run

Message::forMe();

it takes a ton of time to load - ~7seconds. Messages has 704 records and message_user has 1194.

When I run this query in DB directly:

SELECT * FROM messages WHERE id in (select coalesce(parent_id, message_id) from message_user mu join messages m on (mu.message_id = m.id) where mu.user_id = 171) or user_id = 171

It's very fast returning 204 results.

Why is it taking so long as a scope and is there any way to refactor it?

Laravel 5.6



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire