2015-06-20 87 views
2

如何在laravel 5中應用此查詢? 我有3個表,郵政,檔案,評論如何使用laravel雄辯地加入3個表

Post{id,title,body,user_id} 
profile{user_id,last_name,first_name} 
comments{comments,user_id,post_id} 

我想這種結構:

post_id title post last_name first_name

及以下的評論

comments last_name fist_name

回答

17

//樁模型

public function comments(){ 
    return $this->hasMany('App\Comments', 'post_id', 'id'); 
} 

//評論型號

public function user(){ 
    return $this->belongsTo('App\Profile', 'user_id'); 
} 

//剖面模型

public function comments(){ 
    return $this->hasMany('App\Comments'); 
} 

和我使用調用它的控制器:

$posts = Posts::with('userProfile','comments', 'comments.user')->get(); 

然後,它的工作原理:) 謝謝你一些幫助和想法:)

0

如果你只需要那些列,你必須做一些像這樣的事情:

$users = DB::table('comments') 
     ->join('profile', 'comments.user_id', '=', 'profile.user_id') 
     ->select('comments.comments', 'profile.last_name', 'profile.first_name') 
     ->get(); 

無論如何,我會建議,如果你使用的是在不同的地方(或不同的結構)中的數據使用您的模型關係。

P.S:

post_id post last_name first_name 

有沒有 「後」 字段中任何表格,你需要的職稱是什麼?

1

首先,您應該使用Artisan爲您製作模型,例如您創建發佈模型。
那麼你可以這樣做:

$rows = Post::selectRaw('comments.post_id, post.body as post ,profile.last_name, profile.first_name' , comments.comments)-> 
join('profile' , 'post.user_id' ,'=' , 'profile.user_id')-> 
join('comments' , 'post.id' , '=' , 'comments.post_id')-> 
get() ; 

現在你可以訪問任何你從$行需要,像這樣:

foreach($rows as $key=>$row){ 
    echo $row->post_id; 
} 
+0

這return'使用未定義的常量註釋 - 假設'comments'' – Kyrie

+0

任何你想要從$ row變量中獲取的東西,必須首先在你的「selectRaw」語句中定義。 – Salar

+0

問題標題指出「如何使用laravel雄辯連接3個表格」......您發佈的內容使用了Laravel的Raw查詢功能。並不是說它有什麼問題,但這不是特定的,也不是針對雄辯的語法。 –