1
votes

I get the following error when i try this error: Call to undefined method Illuminate\Database\Eloquent\Collection::select() Running this:

Portfolio::find($id)->transactions
        ->select('id','date','symbol','transaction_type','qty','amount');

but this works.

Portfolio::find($id)->transactions

I have a relationship in my portfolio model for

$this->hasMany('Transaction','portfolio_id');

So now to the real question. How can i select certain fields from the transactions table using eager loading? or do i need to do it using query builder

2

2 Answers

2
votes

You may try this:

$portfolio = Portfolio::with(array('transactions' => function($q){
    $q->select(array('id','date','symbol','transaction_type','qty','amount'));
}))->whereId($id)->first();

This will return you Portfolio model along with related transactions and you may use following:

$portfolio->transactions->first()->amount

Also, you may loop them. But following will give you only related models:

Portfolio::find($id)->transactions()
         ->get(array('id','date','symbol','transaction_type','qty','amount'));

Check more on documentation about eager loading.

0
votes

You need to use get instead of select. If you want to select only some specific fields from the database, then you can pass an array to the get method, like in the following example:

Portfolio::find($id)->transactions()
        ->get(array('id','date','symbol','transaction_type','qty','amount'));