以前,我使用以下查询来获取数据
$specialitiesAndRoles = DB::table('user_facility')
->leftjoin('roles', 'user_facility.role_id', 'roles.id')
->leftjoin('specialities','user_facility.speciality_id','=','specialities.id')
->leftjoin('available_specialties','specialities.available_specialties_id' ,'=','available_specialties.id')
->where('user_facility.user_id', $user_id)
->select('user_facility.facility_id','user_facility.speciality_id','user_facility.is_facility_supervisor','user_facility.priv_key','user_facility.role_id','specialities.name','available_specialties.id','available_specialties.specialty_key')
->get();
$specialities = (object)$specialitiesAndRoles;
$response = ['facilities' => $specialities];
我的回答是:
"facilities": [
{
"facility_id": 59,
"speciality_id": 1,
"is_facility_supervisor": 0,
"priv_key": "can_access_patient",
"role_id": 2,
"name": "Medical",
"id": 1,
"specialty_key": "medical_doctor"
现在我正在使用关系并尝试获得相同的响应:
我的关系代码:
$specialitiesAndRoles = UserFacility::with([
'speciality' => function($q)
{
$q->select('id','speciality_key');
},
'roles' => function($q)
{
$q->select('id','name');
},
'availableSpeciality' => function($q)
{
$q->select('id','specialty_key');
}])->get();
我使用关系的响应出现在下面的每个对象中
"facilities": [
{
"id": 2,
"user_id": 32,
"facility_id": 59,
"speciality_id": 1,
"is_facility_supervisor": 0,
"priv_key": "can_access_patient",
"role_id": 2,
"is_admin": null,
"created_at": "2019-07-15 11:30:13",
"updated_at": "2019-07-15 11:30:13",
"isDeleted": null,
"created_by": null,
"updated_by": null,
"is_primary": 0,
"speciality": {
"id": 1,
"speciality_key": "medical_doctor"
},
"roles": {
"id": 2,
"name": "Admin"
},
"available_speciality": {
"id": 2,
"specialty_key": "accu"
},
我不想在不同表的每个数据上创建对象,我只是想做出与使用查询并在上面共享的相同响应。
我如何使用关系做出此回应? 非常感谢您的帮助 预先感谢。
答案 0 :(得分:0)
您可以简单地将查询更改为此:
use App\Models\UserFacitily;
$facilities = UserFacility::leftJoin('roles', 'user_facility.role_id', 'roles.id')
->leftJoin('specialities','user_facility.speciality_id','=','specialities.id')
->leftJoin('available_specialties','specialities.available_specialties_id' ,'=','available_specialties.id')
->where('user_facility.user_id', $user_id)
->select('user_facility.facility_id','user_facility.speciality_id','user_facility.is_facility_supervisor','user_facility.priv_key','user_facility.role_id','specialities.name','available_specialties.id','available_specialties.specialty_key')
->get();