Finding Laravel Where Relationships Don't Exist

I can query where relationships exist using the whereHas method, but now I need to get the opposite result, where the result does not match the result in the whereHas clause.

Here is my request:

$query->whereHas('actions', function ($query) {
    $query->where('actions.created_at', '>', Carbon::now()->addDays(-30));
});

This gets things that have been in effect for the last 30 days, but I need to get something that has NOT been done in the last 30 days.

It seems I need to get max (actions.created_at) from the relationship and see if that value is> 30 days ago, but I'm not sure how I can do this with the eloquent one.

Note: the relationship between the person and the action is from 1 to many, so several action records can be connected, so I can’t just flip the statement as "<="

+4
source share
3 answers

Remember whereHashas more than two parameters:

$query->whereHas('actions', function ($query) {
    $query->where('actions.created_at', '>', Carbon::now()->addDays(-30));
}, '=',0);

Actually it has two more, but by default it is set to '> =' and '1'. Therefore, we add the parameters "=" and "0" (or "<" and "1" for which it is important) to convert it into a subquery, for example, "all actions that are not included in a subset of actions added less than 30 days) .

whereHasmethod: http://laravel.com/api/4.1/Illuminate/Database/Eloquent/Builder.html#method_whereHas

+8
source

Can't you just change your request to smaller or equal?

$query->whereHas('actions', function ($query) {
    $query->where('actions.created_at', '<=', Carbon::now()->addDays(-30));
});
0
source

[]:

$actions = App\Models\Action::all();
foreach($actions as $actionArray){
    $actionCreatedAt = new Carbon($actionArray->created_at);
    $now = Carbon::now();
    $difference = $actionCreatedAt->diff($now)->days;
    if($difference>30){
       $exceedingThirty[] = $actionArray;
    } else {
       continue;
    }
}

$exceedingThirty, .

:

$sql = "DATEDIFF(actions.created_at, '".date('Y-m-d')."' ) > ". 30;
return App\Models\Action::whereRaw( $sql )->get();

, .

0

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


All Articles