【发布时间】:2016-03-31 23:43:06
【问题描述】:
假设我有这些模型:
用户模型
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"
},
]
}
然后我想使用这样的 select raw 添加一列:(不要想1 as number 是多么愚蠢,这只是为了示例。
$usersWithFlights = User::with(['flights'])->addSelect(DB::raw('1 as number'))->get();
我得到这样的数据:
[
{
"userID": 1,
"favoriteColor": green
"flights": []
}
]
问题
addSelect() 方法是针对这种行为而设计的吗?如果不是,是否有其他解决方法来实现这一目标?
注意
我知道我可以在 select 方法中添加类似 Flights.*, Users.* 的内容,但我想知道 addSelect 方法是否可以这样工作
【问题讨论】:
标签: php laravel laravel-5 eager-loading