Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent: how to get related records via whereHas() method?

For example, I can check every post with concrete date.

$users = User::whereHas('posts', function($q){
    $q->where('created_at', '>=', '2015-01-01 00:00:00');
})->get();

But suppose, what to do, if I want to compare a post model date (created_at) with the date attribute of user model?

For example:

$users = User::whereHas('posts', function($q){
    $q->where('created_at', '>=', ** $user->customDate ** ← look this);
})->get();

upd. I use Eloquent outside of Laravel.

like image 704
Stanislav Avatar asked Dec 30 '16 22:12

Stanislav


2 Answers

You can use a raw expression on the Eloquent sub query, by using $q->whereRaw.

In your example:

$users = User::whereHas('posts', function($q){
    $q->whereRaw("created_at >= users.customDate");
})->get();

Unlike DB::raw, this can be used without Laravel's dependency injection of Illuminate\Database facade.

like image 95
DfKimera Avatar answered Nov 15 '22 10:11

DfKimera


Assuming that your users table is just called users you can use DB::raw() to reference a value like you would in a normal query:

$users = User::whereHas('posts', function($q){
    $q->where('created_at', '>=', DB::raw('users.customDate'));
})->get();

Don't forget to either import the DB facade or just change it to \DB::raw(...).

If you're using this outside of Laravel and don't have facades you can cut out the middleman and do:

$q->where('created_at', '>=', new Illuminate\Database\Query\Expression(('users.customDate'));

Hope this helps!

like image 29
Rwd Avatar answered Nov 15 '22 10:11

Rwd