【发布时间】:2021-04-27 13:29:11
【问题描述】:
如果用户选择了没有帖子的类别,我想将他们重定向回来。我已经尝试过这样的事情,但它不起作用:
$check = Category::withCount('posts')->first();
if($cheсk->posts_count < 1){
return redirect()->back()->with('warning', 'No posts in this category!');
}
或者:
if(Category::withCount('posts') < 1){
return redirect()->back()->with('warning', 'No posts in this category!');
}
类别型号:
class Category extends Model
{
use HasFactory;
protected $fillable = [
'name',
'user_id',
'code',
'img'
];
public function posts(){
return $this->hasMany(Post::class);
}
}
【问题讨论】:
-
您能否提及您的类别模型?它有助于更好地理解
-
好的,更新了帖子。
-
第一种方法是正确的,但你总是得到
$check = Category::withCount('posts')->first();,而不是对应于所走路线的类别 -
又该如何正确操作呢?