首页 > 解决方案 > 如何在某些条件下使用 laravel 中的关系从多个表中获取数据?

问题描述

我通过连接多个表从多个表中获取数据,并且关系是一对多和一对一的 一切正常,因为我使用原始方法(直接编写查询)的连接,但我想使用 Laravel 复杂性,这意味着我正在寻找使用 with() has() 或 whereHas() 获得相同的结果。

                                          My Query that works fine in controller

    

$licenses = DB::table('licenses')
            ->join('users as u', 'u.id', '=', 'licenses.user_id')
            ->join('users as sp', 'sp.id', '=', 'licenses.sales_person_id')
            ->join('license_types', 'license_types.id', '=', 'licenses.license_type_id')
            ->select('licenses.*', 'license_types.*', 'u.first_name', 'u.last_name', 'u.email', 'sp.first_name as fname', 'sp.last_name as lname')
            ->where('u.first_name', 'LIKE', '%' . $query . '%')
            ->orWhere('u.last_name', 'LIKE', '%' . $query . '%')
            ->orWhere('u.email', 'LIKE', '%' . $query . '%')
            ->orWhere('sp.first_name', 'LIKE', '%' . $query . '%')
            ->orWhere('sp.last_name', 'LIKE', '%' . $query . '%')
            ->get();


                                        My License Model

public function user()  
{
    return $this->hasOne('App\User','id','user_id');
}
public function license_type()
{   
    return $this->hasOne('App\LicenseType','id','license_type_id');
}



                The Response I get when the above mentioned query is executed
 #items: array:1 [
0 => {#444
  +"id": 1
  +"user_id": 2
  +"sales_person_id": 3
  +"license_type_id": 1
  +"license": "CCVTGS7S0R4M8P7R7S3R"
  +"license_duration": 23
  +"license_expiry": null
  +"allowed_test": "fef"
  +"no_of_devices_allowed": 1
  +"is_deleted": 0
  +"trial_activated_at": "2021-03-10 10:18:04"
  +"license_activated_at": null
  +"user_device_unique_id": "a9dc00sssd6daf79"
  +"is_active": 1
  +"created_at": null
  +"updated_at": null
  +"title": "monthly"
  +"price": "232"
  +"type": 2
  +"first_name": "Mohammad"
  +"last_name": "Fahad"
  +"email": "apexlegendsisracistt@gmail.com"
  +"fname": "Mohammad"
  +"lname": "Fahad"
}

]

我想用 Laravel eloquent 获得相同的结果,但是当我使用 with 时,我不知道如何指定 where 条件并获得相同的输出。

标签: phplaraveleloquent

解决方案


你可以试试这样的

$licenses = License::with(['license_type', 'user', 'salesPerson'])

    ->whereHas('user', function ($q) use ($query) {
        $q->where('first_name', 'LIKE', '%' . $query . '%')
            ->orWhere('last_name', 'LIKE', '%' . $query . '%')
            ->orWhere('u.email', 'LIKE', '%' . $query . '%');
    })
    ->whereHas('salesPerson', function ($q) use ($query) {
        $q->where('first_name', 'LIKE', '%' . $query . '%')
            ->orWhere('last_name', 'LIKE', '%' . $query . '%')
            ->orWhere('u.email', 'LIKE', '%' . $query . '%');
    })->get();

在模型中,您需要创建另一个关系

public function salesPerson()
{
    return $this->hasOne('App\User', 'id', 'sales_person_id');
}

注意这不是确切的解决方案,但您可以根据需要进行修改

参考链接https://laravel.com/docs/8.x/eloquent-relationships#querying-relationship-existence


推荐阅读