I built a commenting system, and I’m working on a page that shows all the comments that are waiting for approval.
The relationship:
Article.php
JavaScript
x
public function comments()
{
return $this->hasMany('AppArticleComment');
}
ArticleComment.php
JavaScript
public function article()
{
return $this->belongsTo('AppArticle');
}
Now, I want to select only the articles that have comments that are waiting for approval (status
column on article_comments
table equals 0
).
Any easy way of doing it? (Of course I can get all articles and check on each one if it has comments)
Advertisement
Answer
The other answer will work but you asked for an easy (also re-usable) approach to use so I would suggest to create a scope
method in your ArticleComment
model using something like the following:
In your Article
model:
JavaScript
use AppArticleComment;
use IlluminateDatabaseEloquentModel;
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();
}
}
In your ArticleComment
model:
JavaScript
// Query scope for pending comments
public function scopePending($query)
{
$query->whereStatus(0);
}
So, you can use something like this:
JavaScript
$posts = Post::has('pendingComments')->get();
Also, you may chain with
like:
JavaScript
$posts = Post::has('pendingComments')->with('pendingComments')->get();