2013-05-31 36 views
2

首先,我以PHP和MVC框架開始,我還不是很擅長這一點,我也做不了很多的問題研究,因爲我真的不知道如何將其翻譯成谷歌搜索。Laravel Eloquent ORM - 返回也屬於第三個對象的對象

和多數民衆贊成也是爲什麼我的問題標題是太有趣了

好了,可以說我有三個型號:帖子,評論者和評論

的意見屬於雙方的帖子和評論者,所以我有這樣的代碼在我的模型,它的一切都很簡單

class Post extends Eloquent { 

    public function comments() { 
     return $this->has_many('Comment'); 
    } 
} 

...

class Commenter extends Eloquent { 

    public function comments() { 
     return $this->has_many('Comment'); 
    } 
} 

...

class Comment extends Eloquent { 

    public function commenter() { 
     return $this->belongsTo('Commenter'); 
    } 

    public function post() { 
     return $this->belongsTo('Post'); 
    } 
} 

然後,我想查詢列出提意見,只有當他們對特定職位

我需要經過評議列表,然後找到誰就擁有屬於該評論意見一個職位。 (我真的不需要擔心因爲它是一個小型數據庫的小實驗項目而成爲最優化的)

我不知道如何將此傳遞給使用控制器的視圖,Commenter::has('comments')將顯示任何具有任何地方都有評論,但我認爲那就是出發點。我也無法在文檔中找到答案。

請讓我知道,如果我沒有做我的問題不夠

+0

請爲我們提供您的Commenter類。 –

+0

現在編輯所有的類 – XuxuBelezA

回答

1

我意識到不會是因爲我想簡單的方法,所以我決定去一個新的多對多關係...

我加

public function posts() { 
    return $this->belongsToMany('Post'); 
} 

public function commenters() { 
    return $this->belongsToMany('Commenter'); 
} 

,現在我可以簡單地使用

->with ('commenters', Post::find($post_id)->commenters()->get()) 

在我的控制器找我提意見

感謝名單幫助,ev回答的人。

2

明確有

class Comment extends Eloquent { 

    public function commenter() { 
     return $this->belongsTo('Commenter'); 
    } 

    public function post() { 
     return $this->belongsTo('Post'); 
    } 
} 

class Commenter extends Eloquent { 

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

} 

class Post extends Eloquent { 

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

} 

您可以

$post = Post::find($givenPostID); 

View::make('posts.comments.listCommenters') 
    ->with('commenters', $post->comments()->groupBy('commenter_id')->get(['commenter_id'])); 

並在視圖

​​

或者你可以創建一個新的物業

class Post extends Eloquent { 

    public function getCommentersAttribute() 
    { 
     $comments = $this->comments; 

     foreach($this->comments as $comment) 
     { 
      /// do whatever you need to grab your list of commenters   
     } 

     return $yourListOfCommenters 
    } 

} 

然後你剛纔提到它你需要的地方:

$post->commenters 
+0

但是,如果我這樣做,它會列出同一作者兩次,如果多於一個評論屬於他。我需要首先查看評論者列表,然後找到屬於該特定帖子的評論者。 – XuxuBelezA

+0

你說得對,但要解決這個問題,我只是在上面添加了一個group。我只是給你一些想法,並不真正解決你的問題,如果你認爲你需要瀏覽評論列表,然後得到所有評論者,那麼你可能需要編寫更多的代碼,查詢爲你做,或者在你的模型上創建一個新方法來獲取評論者列表。 –

+0

groupBy方法可能實際上有幫助,感謝這個想法,但我仍然不知道它是否會爲我做。爲了創建這種新方法,我需要做些什麼? – XuxuBelezA

相關問題