php - 是否有任何选项可以根据 if 条件使用 eloquent 与关系?
问题描述
是否有任何选项可以根据 if 条件使用 eloquent 与关系。我正在尝试根据 if 条件制作一个对象。请查看发布的代码。每次最后一个条件对象返回时。但我需要完整的对象。如果您看到代码,则有两个对象 CountryDetails 和 stateDetails。但此代码仅返回最后一个对象 stateDetails。我需要 CountryDetails 和 stateDetails。
如果您看到代码,则有两个对象 CountryDetails 和 stateDetails。但此代码仅返回最后一个对象 stateDetails。我需要两个对象 CountryDetails 和 stateDetails。
if($registrationFieldObj->country == true){
$userDetails->with(['userMeta'=>function($query){
$query->with(['CountryDetails'=>function($query2){
$query2->select('id','country_name');
}]);
}]);
}
if($registrationFieldObj->state == true){
$userDetails->with(['userMeta'=>function($query){
$query->with(['stateDetails'=>function($query2){
$query2->select('id','country_id','state_name');
}]);
}]);
}
{
"has_error": 0,
"msg": "Successfully Logged in",
"api_token": "ey8S7XN3vdNgFravuw6Zmt8H3n2ol2UX1GA9q4l7XdRcitQymZ7ETv2W4lAk",
"user": {
"id": 2,
"name": "Jhon Smith",
"email": "jhon@yopmail.com",
"phone": "9123378019",
"usertype": "APP",
"profile_pic": "no_profile_img.png",
"status": "A",
"created_at": "2019-07-31 05:17:34",
"updated_at": "2019-08-08 07:36:30",
"user_meta": {
"id": 1,
"user_id": 2,
"address": "Kolkata",
"country_id": 101,
"state_id": 39,
"city_id": 5226,
"pincode": "700001",
"device_id": 458945132565,
"device_token": "fsas576dfsbsfjn6qe7q",
"device_type": "A",
"updated_at": "2019-08-07 13:03:10",
"created_at": null,
"state_details": {
"id": 39,
"country_id": 101,
"state_name": "Uttarakhand"
}
}
}
}
解决方案
将条件放在子查询中
$withCoutry = $registrationFieldObj->country == true;
$withState = $registrationFieldObj->state == true;
$userDetails->with(['userMeta'=>function($query) use ($withCountry, $withState) {
$withArray = [];
if ($withCountry) {
$withArray['CountryDetails'] = function($query2){
$query2->select('id','country_name');
}
}
if ($withState) {
$withArray['stateDetails'] = function($query2){
$query2->select('id','country_id','state_name');
}
}
$query->with($withArray);
}]);
或者如果你摆脱其中的select
一部分
$withCoutry = $registrationFieldObj->country == true; //just to make it simpler
$withState = $registrationFieldObj->state == true;
$withRelation = ['userMeta'];
if ($withCountry) {$withRelation[] = 'userMeta.CountryDetails';}
if ($withState) {$withRelation[] = 'userMeta.stateDetails';}
$userDetails->with($withRelation)->get();
推荐阅读
- python - 有没有办法可以使用 selenium 将网站文本保存到计算机上的 word 文件中?
- android - RecyclerView 中的多个 YouTubePlayer
- html - 是否可以从特定类中选择所有兄弟 div 到下一个?
- ruby - 不带括号的方法调用不会转发所有参数,而带括号的方法调用则不带任何参数进行初始化
- python - 使用 celery-beat 完成上一个任务后,如何在 5 分钟内运行任务?
- javascript - 做出反应。点击更改图片
- angular - 在 IIS 中部署 Okta 的 Angular
- node.js - 如何在不同的 NestJS 模块中引用 Mongoose 模型
- c - 通过 UDP 套接字向 DNS 服务器发送请求
- jquery - 如何在我的图片库中包含带有正确动态文本的按钮