Normal pdo is going to be faster than active record, but naturally the more records the longer any query will take. That's why most large enterprise don't mess with active record, normally you see an implementation of hibernate.
Mar 12, 2017
2
Level 4
Why is Eloquent join with pivot table very slow?
Hi,
I have 3 tables:
- news
- category
- news_category (news_id and category_id)
News model:
public function category()
{
return $this->belongsToMany('App\Models\Category', 'news_category', 'news_id', 'category_id');
}
Category model:
public function news()
{
return $this->belongsToMany('App\Models\News', 'news_category', 'category_id', 'news_id');
}
I need to retrieve news that belong in a certain categories. I do it like this:
$news = News::whereHas('category', function ($query) use($ids) {
$query->whereIN('category_id', [9, 10, 11, 24]);
})
->orderBy('publish_date', 'desc')
->take($limit)
->get();
$limit is usually 6. The problem is that when the news table had less than 1000 records on test database, it worked fast. On the production database we have more than 150.000 records and in that case this gets stuck for a very long time. If I do this query with the query builder it works normally and fast, so it must be the way Eloquent gets the data. Any idea how to make this faster with Eloquent?
Please or to participate in this conversation.