John Davidson

php - Laravel improve exists() boolean queries with eager loading

0 comments
Message:


I'm trying to get rid of queries that look like this:


SELECT EXISTS(
SELECT *
FROM `ignorings`
WHERE `ignorings`.`user_id` = 80101 AND
`ignorings`.`user_id` IS NOT NULL AND
(`ignorable_id` = 79141)
) AS `exists`

SELECT EXISTS(
SELECT *
FROM `favorites`
WHERE `favorites`.`favorited_id` = 341 AND
`favorites`.`favorited_id` IS NOT NULL AND
`favorites`.`favorited_type` = '' App\Review
'' AND `user_id` = 80101
) AS `exists`

I'm trying to do it by eager loading:


auth()->user()->load(['favorite', 'ignoring']);

Here is my User model:


public function ignoring()
{
return $this->hasMany(Ignoring::class);
}

public function isIgnoring($userId)
{
return $this->ignoring()
->where(['ignorable_id' => $userId])
->exists();
}

Here is my blade file:


@if (! auth()->user() || ! auth()->user()->isIgnoring($review->user->id))

How can I get rid of these queries by eager loading a boolean? I want to load all the auth()->users() ignoring relationships, so to speak.



My Answer:
> You can improve these queries by using eager loading in Laravel. Eager loading allows you to load related models along with the main model in a single query, reducing the number of queries executed.

Here's an example of how you can use eager loading to improve the queries you mentioned:

php
// Assuming you have defined relationships in your models

// For the first query
$existsIgnoring = User::where('id', 80101)
->with('ignorings')
->whereHas('ignorings', function ($query) {
$query->where('ignorable_id', 79141);
})
->exists();

// For the second query
$existsFavorite = User::where('id', 80101)
->with('favorites')
->whereHas('favorites', function ($query) {
$query->where('favorited_id', 341)
->where('favorited_type', 'App\Review');
})
->exists();


In the above code, we are eager loading the `ignorings` and `favorites` relationships of the `User` model and then using `whereHas` to filter the related models based on the conditions you specified. Finally, we use the `exists()` method to check if any related models exist that match the criteria.

By using eager loading in this way, you can reduce the number of queries executed and improve the performance of your application.

Rate this post

3 of 5 based on 5658 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us