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

For example, I can check every message with a specific 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 the publication model date (created_at) with the user model date attribute?

For instance:

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

update I use "Eloquent" outside of Laravel.

+4
source share
2 answers

You can use the raw expression in the Eloquent subprocess using $q->whereRaw.

In your example:

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

In contrast DB::raw, this can be used without injection of Laravel facade dependencies Illuminate\Database.

+2
source

, users, DB::raw() , :

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

DB, \DB::raw(...).

Laravel , :

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

, !

+1

Source: https://habr.com/ru/post/1665375/


All Articles