1

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 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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'));

2 Comments

so i tried that and got there error array_key_exists(): The first argument should be either a string or an integer
Use transactions() instead of transactions as I have changed in my answer. If you have done everything else correctly, then that should solve your problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.