dongxinm279890 2017-08-08 11:23
浏览 180
已采纳

Laravel:用于删除数据的控制器功能

I will explain first the tables and how code works

Tables

I have:

  • projects with fields: id, slug, order, public, pathheader and pathhome.
  • project_translations with fields: id, locale, project_id, title and caption.
  • clients with fields: id, name, slug and priority.
  • client_project with fields: id, client_id and project_id

How the code works

When I create a project, I create two project translation too (one for each locale, ex: 'es', 'en'). and then I select a client and this makes the relation client_project.

When I delete the project, I delete at the same time the project_translations which have the same project_id and the client_project row where project_id is the same.

What I want

When I delete the client, delete the row which field client_id have the same value (this is working) and then, delete the projects and projects_translations of the projects which have relation with the client i deleted.

How my function looks for the moment

public function destroyClient($id) //Destruir cliente y todo lo relacionado de la bbdd
    {
        $cliente = Client::find($id); 
        $cliente->delete(); //delete the client
        DB::table('client_project')->where('client_id',$id)->delete(); //delete the client_project relations which field client_id is the same that the client i just deleted.

        return redirect()->route('admin.clients');
    }
  • 写回答

3条回答 默认 最新

  • douti19680318 2017-08-08 11:49
    关注

    Following code will first get all the projects related to client. And then will delete all projects of a client through loop.

    public function destroyClient($id) 
    {
        $cliente = Client::find($id); 
        $cliente->delete(); //delete the client
    
        // get list of all projects of client
        $projects = DB::table('client_project')->where('client_id',$id)->get();
    
        DB::table('client_project')->where('client_id',$id)->delete(); 
    
        // delete all projects of client
        foreach($projects as $project)
        {
            DB::table('projects')->where('id',$project->id)->delete();
    
            DB::table('project_translations')->where('project_id',$project->id)->delete(); 
        }    
    
        return redirect()->route('admin.clients');
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来