2016-06-12 7 views
1

私はコメントシステムを構築しました。私は、承認を待っているコメントをすべて表示するページを作っています。 Laravel 5.2 - コメントのある記事のみを選択する

関係:

Article.php

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

ArticleComment.php

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

は今、私は承認を待っているコメントがある記事だけを選択したい(statusarticle_commentsの表は0に等しい)。

簡単な方法はありますか? (もちろん、私はすべての記事を取得し、それがコメントを持っている場合は、それぞれ1で確認することができます)

答えて

2

他の答えは動作しますが、あなたは私がすることをお勧めします使いやすい(また、再利用可能な)アプローチを求めました次のようなものを使用してArticleCommentモデルでscopeメソッドを作成します。

あなたArticleモデルでは:あなたのArticleCommentモデルで

use App\ArticleComment; 
use Illuminate\Database\Eloquent\Model; 

class Article extends Model { 

    // Relation for comments 
    public function comments() 
    { 
     return $this->hasMany(ArticleComment::class); 
    } 

    // Relation for pending comments 
    public function pendingComments() 
    { 
     return $this->comments()->pending(); 
    } 
} 

// Query scope for pending comments 
public function scopePending($query) 
{ 
    $query->whereStatus(0); 
} 

だから、あなたはこのようなものを使用することができます。また

$posts = Post::has('pendingComments')->get(); 

を、次のようなチェーンwithことがあります。

$posts = Post::has('pendingComments')->with('pendingComments')->get(); 
2
$articles = Article::whereHas('comments', function($query) { 
    $query->where('status', 0); 
}); 
+0

'追加してください - >を取得()'終わりに –

関連する問題