2015-09-04 130 views
2

郵政型號如何從關係中檢索數據?

class Post extends Model 
{ 


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

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

評論模型

class Comment extends Model 
    { 

    public function posts() 
    { 
     return $this->belongsTo('App\Post'); 
    } 


    } 

用戶模型

class User extends Model 
{ 


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

現在我的問題是我怎麼可以訪問屬於後所有評論評論ed用戶名 謝謝你提前

+0

僅具有用戶名你只能夠得到所有評論所有帖子歸特定用戶所有,爲此你可以使用hasManyThrough關係 – zakius

+0

@ zakius.thank你的評論。你發佈你的答案 – iCoders

+0

試試這個'user :: with('post.comment') - > get()' – mdamia

回答

1

嘗試此操作,它將返回所有包含評論的帖子,併爲所選用戶返回包含作者的帖子。

$data = User::with('post.comment') 
     -> with('post.author') 
     -> Where('id',$user_id) 
     -> first(); 

這將獲取與作者的帖子和帖子發表評論與發表評論的用戶。 假設你的模型,這種方式設置,

Post belongs to an Author, 
Author has many Post, 
Post has many Comment 
Comment belongs to a Post 
Comment belongs to a User 
User has many Comment. 

$posts = Post::with('author') -> with('comment.user') -> get(); 
+0

我的要求是。我需要顯示帖子與帖子autoe的名字,並與評論屬於那個帖子與評論username.if你看到我的表結構。存儲評論用戶ID意味着Forign鍵 – iCoders

+0

@vision改變你的查詢,我會更新。 – mdamia

+0

謝謝。我會嘗試 – iCoders

1

你可以做評論的關係查詢,如下所示:

$post_id = 7; 
$username = 'username'; 

$comments = Comment::where('post_id', $post_id)->whereHas('user', function($q) use($username) { 
    $q->where('username', $username); 
})->get(); 
+0

@ Iamzozo.thank你.ii會嘗試 – iCoders