Pedro
Pedro

Reputation: 1477

Get specific columns using “with()” inside of another '

i need to get specific columns in the 2 methods that is being chained inside 'with', but it doesnt work, how can i select specific columns in each method inside of the 'with' method.

Event::with('eventBookmakers.bookmakerInfo')->find(2);

Upvotes: 1

Views: 52

Answers (3)

omitobi
omitobi

Reputation: 7334

Since you're selecting the two interrelated tables (relations) using dot . You may use select() and with() in a closure to add constraint and add the relations as well. So you'll end up with something like:

Event::with(['eventBookmakers' => function($bookmakers){
    $bookmakers->select('id', 'event_id')->with(['bookmakerInfo' => function($info) {
        $info->select('id', 'bookmaker_id');
    }]);
}])->find(2);

Note the event_id passed to the first select ensure the relationship is loaded between Event and EventBookmaker(you can replace it with the relation_id you use instead) and same thing with using bookmaker_id so that it may load relation between Bookmaker and BookmakerInfo

Upvotes: 0

Jesus Erwin Suarez
Jesus Erwin Suarez

Reputation: 1585

Try this, change column name to what column you want to retrieve.

Event::with('eventBookmakers.bookmakerInfo:columnName')->where('id', 2)->get();

or

Event::with('eventBookmakers.bookmakerInfo:columnName')->find(2);

Upvotes: 0

Jonas Staudenmeir
Jonas Staudenmeir

Reputation: 25906

It's possible like this:

Event::with('eventBookmakers:column', 'eventBookmakers.bookmakerInfo:column')->find(2);

Remember to select the foreign key columns (e.g. event_id).

Upvotes: 3

Related Questions