Ashutosh
Ashutosh

Reputation: 4675

Laravel - condition on nested models

I'm writing a code to get nested objects in Laravel. I was wondering if it is possible to write conditions in hasMany or belongsTo.

Here is what I'm doing, that makes the question clear:

$posts = Post::where(
            array(
                'status' => 'active'
            )
        )
        ->orderBy('id', 'asc')
        ->with(['postResponsibilities' => function($query){
            $query->where('status', 'active');
        }])
        ->with(['postRequirements' => function($query){
            $query->where('status', 'active');
        }])
        ->with(['postSalaries' => function($query){
            $query->where('status', 'active');
        }])
        ->skip($limit * ($page - 1))->take($limit)->get();

So, I have to put nested queries to get only those records whose status is active.

In the Post model, I've written:

public function postRequirements(){
    return $this->hasMany('App\Models\PostRequirement', 'post_id');
}

public function postResponsibilities(){
    return $this->hasMany('App\Models\PostResponsibility', 'post_id');
}

public function postSalaries(){
    return $this->hasMany('App\Models\PostSalary', 'post_id');
}

Is there a way such that I can define status condition inside the nested models? So that I can write:

$posts = Post::where(
            array(
                'status' => 'active'
            )
        )
        ->orderBy('id', 'asc')
        ->with('postResponsibilities')
        ->with('postRequirements')
        ->with('postSalaries')
        ->skip($limit * ($page - 1))->take($limit)->get();

I hope the question is clear, thanks

Upvotes: 1

Views: 477

Answers (2)

Oddman
Oddman

Reputation: 3959

What you can do is apply those conditions inside the relationship methods you put on the Post model, for example:

class Post { public function postRequirements() { return $this->hasMany('App\Models\PostRequirement', 'post_id') ->where('status', 'active'); } }

Upvotes: 2

user320487
user320487

Reputation:

Yes it is possible to eager load multiple relationships.

See: https://laravel.com/docs/master/eloquent-relationships#eager-loading

In your case it would be something like:

Post::with('postResponsibilities', 'postRequirements', 'postSalaries')->where()....

Upvotes: 0

Related Questions