【问题标题】:Laravel book on delete remove related all posts and commentsLaravel 关于删除的书删除相关的所有帖子和评论
【发布时间】:2014-08-02 21:44:44
【问题描述】:

这个 sn-ps 来自我的 Book 模型:

 class Book extends \Eloquent
 {  

 public function delete()

     {
         // delete all related cover photos
         $this->cover()->delete();
         // delete all related comments photos
         $this->posts()->comments()->delete();
         // delete all related Blurbs
         $this->posts()->delete();

         // delete the model
         return parent::delete();
     }
 }

在Post 模型中我写道:

 function book() {

         return $this->belongsTo('Book');

     }

     function comments() {

         return $this->hasMany('Comment');

     }

     function user() {

         return $this->belongsTo('User');

     }

 public function delete()
     {

         // delete all related comments also
         $this->comments()->delete();
         // delete the model
         return parent::delete();
     }

在Comment 模型中我写道:

 function posts() {

         return $this->belongsTo('Post');
     }

     function user() {

         return $this->belongsTo('User');
     }

现在,当我试图删除它说的书时。 Call to undefined method Illuminate\Database\Query\Builder::comments()

所以,我知道图书模型删除 cmets 无法正常工作,但不知道如何解决。

【问题讨论】:

  • 为什么不在你的数据库中指定级联删除,让数据库引擎为你做。
  • 但是首先,每次您需要删除一本书时,您需要删除所有关系(与发布和评论相同)?这取决于您的业务逻辑,因此这是对数据库建模的问题。
  • @Razor- 你能给我一个很好的级联删除参考吗?
  • mysql 有据可查(跳转到引用操作)dev.mysql.com/doc/refman/5.0/en/create-table-foreign-keys.html,您也可以查看此答案dba.stackexchange.com/questions/44956/…。但我可以为你的问题给你一个 Laravel 答案。
  • 感谢@Razor,它解决了我的问题

标签: php laravel laravel-4 orm


【解决方案1】:

您可能需要使用正确的索引、外键以及如@Razor 所说的级联更新您的数据库架构...请参阅http://laravel.com/docs/schema#foreign-keys

【讨论】:

    猜你喜欢
    • 2019-08-30
    • 2017-07-03
    • 1970-01-01
    • 1970-01-01
    • 2018-11-12
    • 1970-01-01
    • 1970-01-01
    • 2022-11-10
    • 1970-01-01
    相关资源
    最近更新 更多