【问题标题】:Laravel how to delete a row from multiple tables in one queryLaravel如何在一个查询中从多个表中删除一行
【发布时间】:2014-11-20 01:03:28
【问题描述】:

在我的问答项目中,管理员可以查看所有问题并根据需要删除每个问题。但一个问题 id 有 5 个相关表。也就是说,每个问题 id 都存在于 db 的 5 个表中,当管理员删除一个问题时,我必须根据这个问题 id 从这 5 个表中删除所有条目。

在我的控制器中

DB::table('user_questions')->where('question_id','=',$question_id)->delete();  
DB::table('masters_answers')->where('question_id','=',$question_id)->delete();  
DB::table('masters_questions')->where('question_id','=',$question_id)->delete(); 
DB::table('question_to_category')->where('question_id','=',$question_id)->delete(); 
DB::table('question_to_tags')->where('question_id','=',$question_id)->delete(); 
return Redirect::action('AdminController@anyShowQuestions', array());

上面的代码可以工作,但是有什么方法可以在 laravel 的一个 db 查询中执行相同的过程。?我已经提到了这个post,但找不到适合我的解决方案。如果有人提出正确的方法会很有帮助??

【问题讨论】:

  • 由于记录都是相关的,您可以设置外键约束并将ON DELETE设置为CASCADE

标签: php mysql laravel-4 delete-row


【解决方案1】:

您可以在此相关表上正确设置外键。在迁移中创建密钥时添加onDelete('cascade'),如果一切正常,那么,当您删除问题时,它也会自动删除相关项目。

DB::statement表达式与相应的 SQL 查询一起使用。

例子:

DB::statement('update foo set bar=2');

您需要用纯 SQL 解决您的任务,然后将生成的查询放入 DB::statement 和 viola。

为了帮助您查询,您可以阅读此article 或此StackOverflow post

【讨论】:

    【解决方案2】:

    在你的表上设置外键是最干净的解决方案

    或者,如果你不能使用外键,你可以使用Model Events

    您的每个模型都会触发多个事件,让您可以连接到模型生命周期中的各个点,包括 delete 事件。在你的模型中使用这样的东西:

    class User extends Eloquent {
    
        public static function boot()
        {
            //execute the parent's boot method 
            parent::boot();
    
            //delete your related models here, for example
            static::deleted(function($user)
            {
                foreach($user->user_profiles as $profile)
                {
                    $profile->delete();
                } 
            }
    
        }
    
    }
    

    现在每次删除User 时,所有附加的User_Profile 也会被删除。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-05
      • 1970-01-01
      • 1970-01-01
      • 2010-11-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多