Php Laravel 5.2-仅选择有评论的文章
我建立了一个评论系统,我正在制作一个页面,显示所有等待批准的评论 关系: Article.phpPhp Laravel 5.2-仅选择有评论的文章,php,laravel,laravel-5,eloquent,laravel-5.2,Php,Laravel,Laravel 5,Eloquent,Laravel 5.2,我建立了一个评论系统,我正在制作一个页面,显示所有等待批准的评论 关系: Article.php public function comments() { return $this->hasMany('App\ArticleComment'); } ArticleComment.php public function article() { return $this->belongsTo('App\Article'); } 现在,我只想选择有评论正在等待批准的文章
public function comments()
{
return $this->hasMany('App\ArticleComment');
}
ArticleComment.php
public function article()
{
return $this->belongsTo('App\Article');
}
现在,我只想选择有评论正在等待批准的文章(article\u comments
表中的status
列等于0
)
有什么简单的方法吗?(当然,我可以获取所有文章,并检查每一篇文章是否有评论)另一个答案会起作用,但您要求使用一种简单(也可重复使用)的方法,因此我建议在您的
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);
}
在您的文章评论
模型中:
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();
此外,您还可以将与链接,如:
$posts = Post::has('pendingComments')->with('pendingComments')->get();
另一个答案是可行的,但您要求使用一种简单(也可重复使用)的方法,因此我建议在您的ArticleComment
模型中创建一个scope
方法,使用如下内容:
在您的文章
模型中:
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);
}
在您的文章评论
模型中:
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();
此外,您还可以将与链接,如:
$posts = Post::has('pendingComments')->with('pendingComments')->get();
确保在末尾添加->get()
,确保在末尾添加->get()