Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel search where relationship does not exist

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

Here's my query:

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

This gets things that are actioned in the last 30 days, but I need to get the things that are NOT actioned in the last 30 days.

It seems like I need to get the 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 eloquent.

Note: the relationship between person and action is 1 to many, so there could be multiple action records linked, so I can't just flip the operator to be a "<="

like image 232
vonec Avatar asked Dec 03 '15 12:12

vonec


People also ask

How does Laravel determine the relationship name of a model?

By default, Laravel will determine the relationship associated with the given model based on the class name of the model; however, you may specify the relationship name manually by providing it as the second argument to the whereBelongsTo method:

What is the difference between where () and were not () in Laravel?

Explanation: The were not () is an extension of the where () as discussed earlier and hence can be modified into various forms. The above examples are an illustration of the immense capabilities that the Laravel Framework provides to its users.

What is the has-many-through relationship in Laravel?

The "has-many-through" relationship provides a convenient way to access distant relations via an intermediate relation. For example, let's assume we are building a deployment platform like Laravel Vapor. A Project model might access many Deployment models through an intermediate Environment model.

Is it possible to code in Laravel?

As we have been witness to a few examples, we can safely say, with Laravels vast library and logical command line structure, it is a treat to be able to code in it. The Where not () query is a logical query that searches for items in a given database.


Video Answer


1 Answers

Remember whereHas has more than two parameters:

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

As a matter of fact, it has two more, but by default it is set to '>=' and '1'. So we add the parameters '=' and '0' (or '<', and '1' for what it matters) to convert it in a subquery like 'all the actions that are not in the subset of actions added in less than 30 days).

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

like image 185
Amarnasan Avatar answered Sep 20 '22 02:09

Amarnasan