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

Question

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

Answers 2
Added at 2016-12-30 23:12
Tags
Question

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.

Answers
nr: #1 dodano: 2016-12-31 00:12

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!

nr: #2 dodano: 2016-12-31 01:12

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.

Source Show
◀ Wstecz