如何使用Null合并??php在if语句中的运算符,用Laravel-Eloquents检查对象是否存在



如何使用Null合并??PHP的运算符在if语句中使用Laravel Eloquents来检查对象是否存在?目前,它显示了这个错误:

SQLSTATE[42S22]:未找到列:1054"where子句"中的未知列"posts.categories_id"(SQL:从posts中选择*,其中posts.categories_id=2,posts.categories_id不为空,posts.deleted_at为空(

当类别与帖子不关联时,我尝试自由删除该类别。如果它与一个帖子相关联,那么它只应该显示错误消息

public function destroy(Categories $category)
{
if ($category->posts ?? 0) {
if ($category->posts->count() > 0 ?? 0) {
session()->flash('warning', 'Category have related post. Can't be deleted!');
return redirect()->back();
}
}
$category->delete();
session()->flash('success', 'Category deleted successfully!');
return redirect(route('categories.index'));
}

顺便说一下,我现在有以下关系:

AppPost.php Model 
public function category()
{
return $this->belongsTo(Categories::class);
}
AppCategories.php Model 
public function posts()
{
return $this->hasMany(Post::class);
}

如果我从if条件中删除$category->post,它就起作用了。但随后它会删除所有类型的类别,包括与帖子相关的类别。注:isset($category->post)也给出了错误。

如果可以的话,请帮帮我。谢谢

我想我在这里找到了解决方案。我刚刚通过下面的SQL列重命名语句将列名category_id重命名为categories_id:

alter table posts change category_id categories_id int(11);

并且我现在可以在if语句中访问$category->posts。我认为我的模型名称应该是Category而不是Categories。这就是问题所在,所以我得到了categories_id的默认查找,而不是category_id。顺便说一句,这里现在运行良好。

public function destroy(Categories $category)
{
if ($category->posts) {
if ($category->posts->count() > 0) {
session()->flash('warning', 'Category have related post. Can't be deleted!');
return redirect()->back();
}
}
$category->delete();
session()->flash('warning', 'Category deleted successfully!');
return redirect(route('categories.index'));
}

这种方法现在运行良好。

非常感谢您的帮助

最新更新