dongshan3806 2017-11-10 14:01 采纳率: 0%
浏览 92
已采纳

DB :: transaction()可以执行Eloquent查询作为事务吗?

Me: THIS IS A HYBRID QUESTION | Visitor: (wtf?) what this means?

I'm asking 2 questions in one (as it tightly coupled)

Using: Laravel 5.5 & Mysql

1. How do I delete related models in eloquent?

I'm trying to delete User which has the following relations

belongsTo Address, belongsTo Package, hasMany Orders, hasMany Comments

Orders cascade when User or Product gets deleted COmments cascade when User or Post gets deleted.

Now how do I can delete User & automatically have associated orders & comments deleted?

when I try to delete with $user->delete() laravel throws exception:

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (`cybertron`.`comments`, CONSTRAINT `comments_user_id_foreign` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`)) (SQL: delete from `users` where `id` = 4)

So I decided to use a transaction to delete, User, associated orders & comments, To make sure everything gets deleted.

But I didn't find any transaction in eloquent but in query builder (DB).

2. if I use transaction from DB & use eloquent to delete user ($user->delete) will this consider as a transaction?

like:

DB::transaction(function() {

      $user->comments->delete();
      $user->orders->delete();
      $user->delete();
});

If not then how can I have a transaction with Eloquent ?

Any help will be greatly appreciated

  • 写回答

2条回答 默认 最新

  • douwei7203 2017-11-11 09:54
    关注
    1. You have Eloquent events For deleting but you can also override default delete method like so:

      public function delete()
      {
          \DB::transaction(function() {
              $this->comments()->delete();
              $this->orders()->delete();
              parent::delete(); 
           });
      }
      
    2. Yes, Eloquent doesn't have transaction itself. You use transactions as you showed and wrap Eloquent or query builder in it. Be aware that in your case you should use comments() and orders() instead of comments and orders

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)