简体   繁体   English

Laravel 5.4删除一对多关系

[英]Laravel 5.4 delete one to many relationship

I want to delete a record on a table if no one use it on another. 如果没有人在另一个表上使用记录,我想删除它。

For example, if I delete all articles in a category, I want to delete this category too because no one use it. 例如,如果我删除一个类别中的所有文章,我也想删除该类别,因为没有人使用它。

Is there a simple way to do it with laravel ? 有使用laravel进行操作的简单方法吗?

Thank 谢谢

Use laravel doesntHave method to delete all categories that doesn't have articles. 使用laravel doesntHave方法删除所有没有文章的类别。

Something like this 像这样

category::doesntHave('articles')->delete();

You can read more about this in the official document here 您可以在此处的官方文档中了解更多信息

When you check to see if a category has any articles, you can just delete the category if there aren't any. 当您检查某个类别中是否有任何文章时,如果没有任何文章,则可以删除该类别。 For example: 例如:

if(!$category->articles->count()){
   $category->delete();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM