2015-10-05 69 views
1

我正在連接兩個表,然後找到指定的記錄,但不幸的是它不起作用。查詢生成器加入並獲取指定的記錄laravel

$users = DB::table('users') 
     ->join('user_details', 'users.id', '=', 'user_details.id') 
     //->select('users.*', 'contacts.phone', 'orders.price') 
     ->get()->find(1); 

任何想法都有幫助嗎?

+0

你有沒有理由不使用雄辯? – Tim

+0

即時通訊還不擅長。即時通訊同時使用eloqouent和查詢生成器,但到目前爲止,即時通訊使用查詢生成器來解決這個問題。如果你可以建議使用eloqouent來實現它,那麼就會愛上你的。 –

+0

你是什麼意思具體記錄? – aldrin27

回答

0

我認爲,正確的查詢將會象下面這樣:

$users = DB::table('users') 
    ->find(1) 
    ->join('user_details', 'users.id', '=', 'user_details.id') 
    ->get(); 

或者您可以使用where指定where子句。

$users = DB::table('users') 
    ->where('user.gender', '=', 1) // Example. 
    ->join('user_details', 'users.id', '=', 'user_details.id') 
    ->get(); 
+0

不幸的是,我得到這個錯誤「調用未定義的方法stdClass :: join()」的任何想法?即時通訊使用您的答案中的第一個代碼。 –

+0

,我得到了這個錯誤「SQLSTATE [42S22]:未找到列:1054'where子句'中的未知列'user.id'(SQL:select * from用戶'內部連接'user_details'在'用戶'上.'id '='user_details'.'id' where'user'.'id' = 1)「在我嘗試第二個之後,有什麼想法? –

+0

@CodeDemon在您的問題中發佈您的表格架構 –

1

要使用口才實現這一點,請執行下列操作:

我假設你正在使用最新版本Laravel(5.1)

1.你需要一個模型用戶和所述的UserDetails:

<?php 

namespace App; 

use Illuminate\Database\Eloquent\Model; 

class User extends Model {} 

2.設置第它們之間的關係ë

user.php的

function details() 
{ 
    // for this to work, the user_details table needs a column user_id 
    return $this->hasMany('App\UserDetail'); 
} 

UserDetail.php

function user() 
{ 
    return $this->belongsTo('App\User'); 
} 

3.查詢的關係:

例如UserController.php

<?php 

namespace App\Http\Controllers; 

use App\User; 

class UserController { 
    public function index() 
    { 
     $user = User::find(1); 
     $user_details = $user->details; 

     // or 

     $user = User::find(1)->with('details'); 

    } 
} 
+0

那麼我該如何去查詢它然後我做了那裏關係的設置? –

+0

對不起,我在第一個答案中忘了它。請看我編輯的一個。 – Tim

+0

不錯。我的用戶表有ID不是user_id,也是相同的uses_detals主鍵列有一個名爲「ID」是好嗎?如何使用它,就像你說的它必須有「user_id」 –