Php Laravel 5.1选择带有功能的字段
我可以从与函数“with”的关系中选择值吗? 所以做一些如下的事情:Php Laravel 5.1选择带有功能的字段,php,laravel,laravel-5,eloquent,Php,Laravel,Laravel 5,Eloquent,我可以从与函数“with”的关系中选择值吗? 所以做一些如下的事情: $test = User::where('id',1)->with(['user_detail' => function($query){ $query->select("detail_1"); }])->get(); 是的,我知道我可以将select放在与“用户详细信息”相关的位置,但我可以使用函数进行选择吗?是的,您可以使用select()内部with()。
$test = User::where('id',1)->with(['user_detail' => function($query){
$query->select("detail_1");
}])->get();
是的,我知道我可以将select放在与“用户详细信息”相关的位置,但我可以使用函数进行选择吗?是的,您可以使用
select()
内部with()
。只需传递一个列数组:
$query->select(['detail_1', 'detail_2']);
或者,您可以创建另一个关系,并向其中添加select()
:
public function userDatails()
{
return $this->hasMany('App\UserDetail')->select(['detail_1', 'detail_2']);
}
您可以使用在
中进行选择,如下例所示:
$test = User::where('id',1)->with(['user_detail' => function($query){
$query->select("detail_1");
}])->get();
但它不起作用(正如您在其他答案中所评论的),因为您只选择了一个属性,但外键在select语句中不可用。因此,请确保您也选择了相关的外键,然后它就可以工作了
在您的情况下,我认为您还必须在选择中选择用户id
,例如:
$test = User::where('id',1)->with(['user_detail' => function($query){
$query->select(
'user_id', // This is required if this key is the foreign key
'detail_1'
);
}])->get();
因此,如果没有建立关系的外键
,雄辩的
将无法加载相关模型,这就是为什么正如您在其他注释中提到的,结果中会出现null
。对于第二个解决方案,可以,但是对于第一个解决方案。不跟我一起工作。模型中“用户详细信息”字段返回空。请添加说明。
$result = Staff::where('live_status',2)
->with('position')->with('department')->with('gender')
->with(['partner' => function($query){
$query->where('alive',0);
}]);