为什么Laravel没有返回特定用户的关系记录(它返回所有用户的记录)?

This is a very weird situation. I don't know if it's some issue with my understanding or a bug in Laravel Eloquent ORM. But here's what is happening.

I have one table called users and another called user_metas. One table contains all the user data obviously and the another table (user_metas) has 4 columns as follows.

  • id
  • user_id
  • name
  • value

Now, there are 4 records in this table that I want to fetch FOR A SPECIFIC USER. They are as follows.

  • name => region_name
  • name => region_code
  • name => country_name
  • name => country_code

I have a hasMany and belongsTo relationship defined in User.php and UserMeta.php respectively. And here is how I am trying to fetch the above given rows from a user_metas table.

$user->meta()->where('name','like','region%')->orWhere('name','like','country%')->pluck('value','name');

The problem is, It is returning all the records that match region% and country% from the whole freaking table even though I have requested the data for a specific user only! It should filter out other records automatically!

I don't know what's wrong. Maybe I misunderstood the feature or something's up with Eloquent ORM. Can anyone spread some knowledge here?

Update: using toSql function, I figured out that it is using conditions directly instead of grouping them. It means, the condition is like this user_id = ? AND name = ? OR name = ? instead of user_id = ? AND (name = ? or name = ?).

Finally, I figured it out! The only thing I had to do is to pass a closure to the where function and write down the conditions. Here is my old code and the new code that is working.

Old code:

$user->meta()->where('name','like','region%')->orWhere('name','like','country%')->pluck('value','name');

New Code:

$user->meta()->where(function($q){
     $q->where('name','like','country%')
       ->orWhere('name','like','region%');
})->pluck('value','name');

And things worked out the way I wanted! Laravel always has perfect solutions!