laravel:whereHas查询获取三个表数据

时间:2018-04-23 06:38:36

标签: laravel laravel-5.5

定义一个简单的查询以获取三个表数据

users, 表格1}}, 表user_details

在我的user_device_datas上定义一个函数,以便从LoginController模型中获取数据。

UserDetails
$userInformation = UserDetails::userDetail($user->id); 模型上的

定义关系

User

public function UserDeviceData() { return $this->hasMany(UserDeviceData::class); } public function UserDetails() { return $this->hasOne(UserDetails::class); } 模型上,我的查询数据看起来像

UserDetails

我得到的回应:

 public static function userDetail($id){
     $result = User::whereHas('userDetails',function($query)  use ($id) {
           $query->where('user_id',$id); 
        })->whereHas('UserDeviceData',function($query)  use ($id) {
           $query->where('user_id',$id);
        })->where('user.id', $id)
        ->with('userDetails','UserDeviceData')
        ->first();
} 

我没有收到关于查询的 "userInfo": { "id": 2, "name": null, "email": "test@test.com", "phone": null, "address": null, "company": null, "description": null, "device_id": null, "system_role": "User", "status": "Active", "otp_verify_id": "253526851", "parent_id": 0, "last_login": "2018-04-23 12:03:43", "profile_picture": null, "business_card_pic": null } 数据。我的代码中出现了什么错误?

1 个答案:

答案 0 :(得分:2)

import java.util.Scanner;

public class StackOf4 {

    public static void main(String[] args) {

        Scanner scn=new Scanner(System.in);

        String[] names=new String[5];


        for(int i=0;i<5;i++) {


            System.out.println("Enter a string:");
            names[i]=scn.nextLine();

        }

        System.out.println("The strings with more than 4 characters are: ");

        for(int i=0;i<5;i++) {

            if(names[i].length()>4)
            System.out.println(names[i]);

        }


    }


}

你必须使用public static function userDetail($id){ $result = User::whereHas('userDetails',function($query) use ($id) { $query->where('user_id',$id); })->whereHas('UserDeviceData',function($query) use ($id) { $query->where('user_id',$id); })->where('users.id',$id) ->with(['UserDetails' => function($query) use ($id){ $query->where('user_id',$id); }, 'UserDeviceData' => function($query) use ($id){ $query->where('user_id',$id); } ]) ->first(); return $result ; } 来获得关系。