How addSelect() Builder method works in Laravel

ggderas picture ggderas · Apr 1, 2016 · Viewed 30.5k times · Source

Say I have these models:

User Model

namespace App;

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'User';

    protected $fillable =
    [
       'username', 'favoriteColor'
    ];          

    public function flights()
    {
        return $this->hasMany('App\Flight');
    }
}

Flight Model

namespace App;

use Illuminate\Database\Eloquent\Model;

class Flight extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'Flight';

    protected $fillable =
    [
       'flightName', 
    ];              
}   

I'm trying to do something with eager loading, whenever I do this:

$usersWithFlights = User::with(['flights'])->get();

I get data like this: (Which if fine, is what I expect)

{
    "userID": 1,
    "favoriteColor": green
    "flights": 
    [
       {
           "flightID": 2240,
           "flightName" : "To Beijing fellas"
       },
       {
           "flightID": 4432,
           "flightName" : "To Russia fellas"
       },       
    ]
}

But then I want to add a column using a select raw like this: (Don't think about how silly the 1 as number is, it's just for the sake of the example.

$usersWithFlights = User::with(['flights'])->addSelect(DB::raw('1 as number'))->get();

I get the data like this:

[
    {
        "userID": 1,
        "favoriteColor": green
        "flights": []
    }
]

QUESTION

Was the addSelect() method made for this kind of behaviour? If not are other work arounds in order to achieve this?

NOTE

I know I could add in the select method something like Flights.*, Users.* but I want to know if the addSelect method works that way

Answer

plaha picture plaha · Jul 25, 2017

If you need default values from select and add some extra, you can use this construction:

$usersWithFlights = User::with(['flights'])->select()->addSelect(DB::raw('1 as number'))->get();