首页 > 解决方案 > Laravel 选择多个字段返回 null

问题描述

我有这个查询来从 3 个表中检索一些字段值。问题是如果所选字段之一为空或 null,即使其他字段不为 null 且包含值,查询也会返回 null。即使这些字段的某些值为空或为空,我也想检索所选字段的值。

public function Profile(Request $request)
{
    # get profile Data for User
    # data from application userID
    # data retrive  to application username   address phone
    $profileData =  DB::table('users')->where('userId','=',$request['userId'])
    ->join('patients','users.userId','=','patients.UID')
    ->join('states','users.stateId','=','states.stateId')
    ->join('gender','users.genderId','=','gender.genderId')
    ->select('users.fullName','users.address','users.userPhone','states.stateName',
    'patients.hight','patients.weight','patients.bloodGroup'
    ,'gender.type')
    ->first();

    return response()->json(['data' => $profileData]);
}

标签: phplaravelapi

解决方案


即使第二个表中没有行,也要从主表中获取所有条目,您应该使用左连接

$profileData =  DB::table('users')->where('userId','=',$request['userId'])
    ->leftJoin('patients','users.userId','=','patients.UID')
    ->leftJoin('states','users.stateId','=','states.stateId')
    ->leftJoin('gender','users.genderId','=','gender.genderId')
    ->select('users.fullName','users.address','users.userPhone','states.stateName',
    'patients.hight','patients.weight','patients.bloodGroup'
    ,'gender.type')
    ->first();

推荐阅读