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.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With