php – 如何在Laravel中使用addSelect()Builder方法
发布时间:2020-12-14 19:36:19 所属栏目:大数据 来源:网络整理
导读:说我有这些模型: 用户模型 namespace App;use IlluminateDatabaseEloquentModel;class User extends Model{ /** * The table associated with the model. * * @var string */ protected $table = 'User'; protected $fillable = [ 'username','favoriteC
说我有这些模型:
用户模型 namespace App; use IlluminateDatabaseEloquentModel; 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('AppFlight'); } } 飞行模型 namespace App; use IlluminateDatabaseEloquentModel; 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(); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |