2016-02-10 36 views
1

我有一個名爲records的表,其中user_id列鏈接到users表以設置所有權。Laravel帶有多個表的搜索DB

我可以正確地過濾由title記錄與搜索字符串:

$records->where('title', 'LIKE', '%'.$search.'%'); 

但我想也返回一個包含users.firstnameusers.lastname的結果,這是我的(可怕)加入嘗試:

$records->join('users', 'users.id', '=', 'records.user_id') 
     ->where('users.firstname', 'LIKE', '%'.$search.'%') 
     ->orWhere('users.lastname', 'LIKE', '%'.$search.'%') 
     ->orWhere('title', 'LIKE', '%'.$search.'%'); 

// SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in order clause is ambiguous 

回答

0

雖然我等待一個更好的答案,我發現這工作,但的解決方案是不是最優的,因爲它涉及到一個額外的查詢收集作者user_id,並用它隨後查詢records

// Get the author ID 
$author = DB::table('users') 
       ->select(DB::raw('CONCAT_WS(" ",`firstname`,`lastname`) as `fullname`,id')) 
       ->having('fullname', 'LIKE', '%'.$search.'%') 
       ->first(); 

// $author output: 
stdClass Object 
(
    [fullname] => John Doe 
    [id] => 35 
) 

// Query the records using the gathered ID 
$records->where('user_id', $author->id) 
     ->orWhere('title', 'LIKE', '%'.$search.'%'); 

此解決方案的問題:除了額外的查詢,如果有人搜索John DoeSome Title,結果是正確的。但是,如果搜索John Doe Some Title,則不會顯示任何內容,因爲找不到作者和標題。

-1

您需要設置也使用搜索參數在你的內部查詢:

$records->join('users', function($join) use ($search) 
{ 
    $join->on('users.id', '=', 'records.user_id') 
     ->where('users.firstname', 'LIKE', '%'.$search.'%') 
     ->orWhere('users.lastname', 'LIKE', '%'.$search.'%'); 
}); 
+0

謝謝,但我去掉了不必要的代碼,以保持它乾淨。我會更新示例以避免混淆。 – gyo

0

如果我瞭解您想通過使用$ search進行過濾來返回記錄結果,並且還想顯示此記錄的用戶信息。 您可以使用Eloquent。 您的模型必須是:
在用戶模式:

public function records() 
    { 
     return $this->hasMany(Record::class); 
    } 

在拍攝模式:

public function user() 
    { 
     return $this->belongsTo(User::class); 
    } 

並在控制器:

Record::where('title', 'LIKE', '%'.$search.'%') 
      ->with('user') 
      ->first(); 
+0

我希望返回搜索查詢「John Doe」的所有「記錄」,但「firstname」和「lastname」位於「users」表中,而不是「records」表中。另外,我還想返回'John Doe Some Title'的記錄,其中'John Doe'位於'users'表中,'records'表中的'Some Title'位於'users'表中。 – gyo