3

I'm trying to get an Eloquent collection with the next line:

Document::with('more_information')->anyScope()->get()

I'm getting a collection with 20 "columns", but I want to add another one to format a date in order to easily interact with other components instead of format the date in each component.

To add this column I can rewrite the 21 column names and write more lines to get the collections that invoke with my with...but that doesn't look good...

Is there a way to simply to add my 21st column without rewrite the other 20?

I read something about addSelect, but in my code it ignores my 20 first columns

1
  • Is this 21st column just a different representation of another column taken from the database? Commented Mar 10, 2016 at 23:51

1 Answer 1

4

Finally got it, it works doing the next:

Document::with('more_information')->anyScope()->get('*',<aditional columns>)

Update: Looking for another more suitable way to get my task done, I found a mixture between accessors and the Model property $appends

Using next script I'm able to retrieve my collection with a custom column. It's important to mention that if you don't use $appends, the accessor works well but it's not returned within the array. It's not recommended to use a lot of times $appends because it affects in a negative way the performance

class Trabajador extends Model {

    protected $appends = ["fullName"];

    public function getFullNameAttribute() {
         return $this->attributes['nombre'] . $this->attributes['apellidos'];
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

This works nicely if you can do your calculations in PHP. However, I have a need to run the calculation in the SQL query running on the database. Specifically I need to run a json_agg() calculation in my Postres database, which is not an easy thing to replicate in PHP. Any ideas on how to do this would be muchos welcome.

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.