dpwqicw157673 2017-08-01 18:18
浏览 71

Laravel触摸(递归)

Question: how to touch a model from the same model?

Details: I'm using Laravel 5.4 to build an application for renting books between people. In each transaction there are 2 parts: information concerning the owner VS information concerning the person who is renting the book.

Because the the 2 sides, I chose to use only one table named rents for both sides. To distinguish which is which I added a field rent_side that contains 'owner' or 'borrower'. This makes it easy if I want to show/search a history of a person. If had 2 ore more tables, I would have to make a UNION to select all the data needed to show the history.

These two sides are coupled together thanks to common id called couple_id.

From each side, I can see the opposed side thanks to method located in the model App\Rent I named reverse, where I do the following:

public function reverse()
{
    return $this->hasOne('App\Rent', 'couple_id', 'couple_id')
        ->where('id', '!=', $this->id);
}

Because I need to update the parent timestaps and according to laravel documentation I used the following:

protected $touches = ['reverse'];

The problem is that this touching affects the same model. So when I update/insert a new record, the request takes up to 4min before sending an error. As if it went into an endless loop.

Is there a way to touch a model from the same model?

  • 写回答

1条回答 默认 最新

  • dscc90150010 2017-08-01 18:47
    关注

    The source code here does indeed show that it would result in an infinite loop.

    What I suggest is you do the following:

    class Rent extends Model {
          protected $touches = [ "reverse" ];
    
          protected function touchOwners() {
               static $recursionCount = 0;
               if ($recursionCount <= 1) {
                  $recursionCount++:
                  parent::touchOwners();
               } else {
                 $recursionCount=0;
               }
          }
    }
    

    Haven't tested it so not 100% sure it would work.

    Alternatively what would work would be:

    Manually ensure you're touching the related model whenever you save a model

    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?