我想创建一个功能,该帖子需要5个管理员批准才能显示。创建帖子后,帖子将存储在帖子表中。默认情况下,该帖子的批准列为false。为了显示帖子,需要5个管理员中的3个批准。所以我想从数据库中获取帖子并在管理面板中显示。每次都会随机显示1个帖子给管理员。如果管理员批准了帖子。批准将存储在其他表名称Approvals中。
模型是
发布模型
public function user(){
return $this->belongsTo('App\User');
}
public function post(){
return $this->belongsTo('App\Forum\Post');
}
在审批模式中
protected $fillable = [
'admin_id',
'post_id',
'approved'
];
public function admin(){
return $this->belongsTo('App\Admin');
}
public function post(){
return $this->belongsTo('App\Forum\Post');
}
在我的控制器中,我使用此功能获取随机未经批准的帖子。但是现在我需要过滤掉帖子,如果批准表包含管理员之一的批准数据。他/她不会再看到这个帖子了。
$post = Post::inRandomOrder()->where('approved', false)->first();
如果它可能有很多帖子要批准。我怎么知道管理员被批准了帖子,所以相同的帖子不会再显示给同一个管理员。
答案 0 :(得分:0)
post()
模型中的Post
关系似乎是一个错误。我认为它应该是与你的Approval
模型的关系,对吗?首先,在Post模型中,将post()
方法替换为:
public function approvals() {
return $this->hasMany('App\Forum\Approval');
}
然后,这是您查询的一种方法:
$post = Post::inRandomOrder()->where('approved', false)
->with('approvals')
->get()
->filter(function($value, $key) {
// A post without any approvals yet is OK
if ($value->approvals->count() === 0) {
return true;
}
// If it has approvals, check the current admin isn't one of them
return !$value->approvals->contains('admin_id', \Auth::user()->id);
})
->first()