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

Alex
  • 21,273
  • 10
  • 61
  • 73
WindSaber
  • 323
  • 1
  • 3
  • 15
  • Is this 21st column just a different representation of another column taken from the database? – Bogdan Mar 10 '16 at 23:51

1 Answers1

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'];
    }
}
Ramin eghbalian
  • 2,348
  • 1
  • 16
  • 36
WindSaber
  • 323
  • 1
  • 3
  • 15
  • 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. – cartbeforehorse Sep 20 '17 at 10:59