说我有这些模型:
用户模型
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'); } }
飞行模型
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',]; }
每当我这样做时,我都会尝试用急切的加载做一些事情:
$usersWithFlights = User::with(['flights'])->get();
我得到这样的数据:(如果没问题,那就是我的期望)
{ "userID": 1,"favoriteColor": green "flights": [ { "flightID": 2240,"flightName" : "To Beijing fellas" },{ "flightID": 4432,"flightName" : "To Russia fellas" },] }
但后来我想使用这样的选择原始添加一个列:(不要考虑数字1是多么愚蠢,这只是为了示例.
$usersWithFlights = User::with(['flights'])->addSelect(DB::raw('1 as number'))->get();
我得到这样的数据:
[ { "userID": 1,"favoriteColor": green "flights": [] } ]
题
是否为这种行为制作了addSelect()方法?如果没有其他工作来实现这一目标?
注意
我知道我可以添加像Flight,*,Users.这样的select方法.但是我想知道addSelect方法是否以这种方式工作
解决方法
如果你需要select中的默认值并添加一些额外的值,你可以使用这种结构:
$usersWithFlights = User :: with([‘flights’]) – > select() – > addSelect(DB :: raw(‘1 as number’)) – > get();