When you use eager loading like this you get ALL users and only images that pass the constraint. Your constraint for image is that user_id == 'image_id'. So I think you get no images.
[L5] Weirdness in Querying Many to Many relation
Well, this is strange.
I have User and Images models with many to many relation. And now when I run this
User::with(['images' => function($query){
$query->where('user_id', 'image_id');
}])->get();
I get all the users.
When I saw the query with the help of Laravel" target="_blank">https://github.com/barryvdh/laravel-debugbar'>Laravel Debugbar
I found that it was checking the 'user_id' column with the (string) 'image_id'.
so technically I should not get any result as query fails coz i dont have 'image_id' string in my user_id column.
But I get all the users. (Strange).
And when i run the build query in phpmyadmin i get no result as expected.
This is the build query I got from Laravel Debugbar
select `images`.*, `image_user`.`user_id` as `pivot_user_id`, `image_user`.`image_id` as `pivot_image_id` from `images` inner join `image_user` on `images`.`id` = `image_user`.`image_id` where `image_user`.`user_id` in ('1', '7', '8', '9', '10', '11') and `user_id` = 'image_id'
Ok, now I fix the query like this.
User::with(['images' => function($query){
$query->where('user_id', '`image_id`');
}])->get();
And the build query for this is
select `images`.*, `image_user`.`user_id` as `pivot_user_id`, `image_user`.`image_id` as `pivot_image_id` from `images` inner join `image_user` on `images`.`id` = `image_user`.`image_id` where `image_user`.`user_id` in ('1', '7', '8', '9', '10', '11') and `user_id` = '`image_id`'
Which is perfect. And when i run it in phpmyadmin i get only users I requested for.
But in Laravel, Again it gives me all the users. (Strange again).
This is little weird to me. Does anyone know why is it happening? Any clue?
Doesn't work with eager loading but could work with whereHas and a raw where :
$users = User::whereHas('images', function($q)
{
$q->whereRaw('users.id = images.id');
})->get();
Please or to participate in this conversation.