cskiwi's avatar

multiple with

hi,

I was wondering if you can have multiple with preset? Say I have a model called match and that has 2 teams.

but every time I want to call the match with those teams I have to do:

public function show($id){
        return Match::with('team1')->with('team2')->find($id);
}

And there are more foreign keys to other models in the pipeline. is there a way to say Match::with('info') and I can predfine what to include then?

0 likes
2 replies
bobbybouwmann's avatar
Level 88

You can create a query scope for that I guess. You need to define a function in your model like this:

// App\Match.php

public function scopeInfo($query)
{
    return $query->with('team1', 'team2')
}

Now you can do this in your controllers

public function show($id)
{
    return Match::info()->find($id);
}

Source: http://laravel.com/docs/5.0/eloquent#query-scopes

8 likes
cskiwi's avatar

Yep that totally did it :) thanks!

Please or to participate in this conversation.