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
On Laravel 6, I'm finding that addSelect() is replacing the whole select list with the single column in the select terms instead of adding to them. I'm using $hidden to hide some very large columns, so maybe that is affecting it. But just pointing out this method is potentially not as robust as expected.
In Laravel the database query builder provides an easy interface to create and run database queries. It can be used to perform all the database operations in your application, from basic DB Connection, CRUD, Aggregates, etc. and it works on all supported database systems like a champ.
Introduction. Laravel's database query builder provides a convenient, fluent interface to creating and running database queries. It can be used to perform most database operations in your application and works perfectly with all of Laravel's supported database systems.
When you are handling more data, it is better to use Laravel's DB facade query builder than Laravel's Eloquent ORM. From performance tests, inserting 1000 rows in a simple table takes Eloquent 1.2 seconds whereas the DB facade takes only 800 milliseconds. It has a simpler syntax than the DB facade.
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With