为了避免模型监控器死循环调用,我们使用 DB 类直接对数据库进行操作

教程中有一段注释“为了避免模型监控器死循环调用,我们使用 DB 类直接对数据库进行操作”,请问什么情况会造成死循环调用?可否举个例子?谢谢。

《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L02 从零构建论坛系统》
以构建论坛项目 LaraBBS 为线索,展开对 Laravel 框架的全面学习。应用程序架构思路贴近 Laravel 框架的设计哲学。
最佳答案
class TopicObserver
{
    public function saving(Topic $topic)
    {
        // 如 slug 字段无内容,即使用翻译器对 title 进行翻译
        if ( ! $topic->slug) {
            $topic->slug = app(SlugTranslateHandler::class)->translate($topic->title);
        }
    }
}

TopicObserver 检测到 saving 的时候会触发 \DB::table('topics')->where('id', $this->topic->id)->update(['slug' => $slug]); ,如果在这里写成这样。

public function handle()
{
    // 请求百度 API 接口进行翻译
    $slug = app(SlugTranslateHandler::class)->translate($this->topic->title);

    // 为了避免模型监控器死循环调用,我们使用 DB 类直接对数据库进行操作
    // \DB::table('topics')->where('id', $this->topic->id)->update(['slug' => $slug]);
    $this->topic->slug = $slug;
    $this->topic->save(); //  <------这里又会再次触发 saving 事件,形成死循环,所以不能这样写。
}
5年前 评论
讨论数量: 1
class TopicObserver
{
    public function saving(Topic $topic)
    {
        // 如 slug 字段无内容,即使用翻译器对 title 进行翻译
        if ( ! $topic->slug) {
            $topic->slug = app(SlugTranslateHandler::class)->translate($topic->title);
        }
    }
}

TopicObserver 检测到 saving 的时候会触发 \DB::table('topics')->where('id', $this->topic->id)->update(['slug' => $slug]); ,如果在这里写成这样。

public function handle()
{
    // 请求百度 API 接口进行翻译
    $slug = app(SlugTranslateHandler::class)->translate($this->topic->title);

    // 为了避免模型监控器死循环调用,我们使用 DB 类直接对数据库进行操作
    // \DB::table('topics')->where('id', $this->topic->id)->update(['slug' => $slug]);
    $this->topic->slug = $slug;
    $this->topic->save(); //  <------这里又会再次触发 saving 事件,形成死循环,所以不能这样写。
}
5年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!