jeudi 31 mars 2016

How addSelect() Builder method works in Laravel

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



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/1X0W0vb
via IFTTT

Aucun commentaire:

Enregistrer un commentaire