在哪里子句laravel内部查询

时间:2018-08-23 06:59:44

标签: mysql laravel laravel-query-builder

我有一个数据库,其中有两个表driver_company_mapcompany,我要做的是从company_code表中获得driver_company_map并将其传递给where子句在company表上执行的另一个查询中,我两个单独的查询都像这样

$result = DB::connection($this->masterDb)->table('driver_company_map')
        ->where('driver_code', $driverCode) //i get the $driverCode from function parameter
        ->select('company_code')
        ->first();
        $companyCode = $result->company_code;

我在下面的查询中使用上面的$companyCode

$result = DB::connection($this->masterDb)->table('company')
        ->where('code', $companyCode)
        ->select('db_connection')
        ->first();
        $clientDb = $result->db_connection;

上面的逻辑工作正常,但我都想作为嵌套查询我尝试过,但是下面的代码却没有给出正确的结果

$result = DB::connection($this->masterDb)->table('company')
        ->where('code', function($companyCode_query){
            $companyCode_query->select('company_code')
            ->from('driver_company_map')
            >where('driver_code', $driverCode);
        })->get()
        ->select('db_connection')
        ->first();
        $clientDb = $result->db_connection;

1 个答案:

答案 0 :(得分:0)

尝试一下:

$result = DB::connection($this->masterDb)->table('company')
    ->select('db_connection')
    ->join('driver_company_map', 'company.code', 'driver_company_map.company_code')
    ->where('driver_company_map.driver_code', $driverCode)
    ->first();

请参阅: https://laravel.com/docs/5.6/queries#joins