Laravel 使用多对多关联添加数据时 observer 的 created 方法不执行是什么原因?

Laravel使用attach添加数据时observer的created方法不执行是什么原因?

问题:

关注接口没有触发observer, 而评论接口触发了oberser, 两者区别是一个使用的attch方法,另一个使用时create方法,请问是否是attach方法的原因?如果是,为什么attach方法不能触发observer?代码如下

接口

// 关注接口
 public function follow(Post $post){
     // observer没有调用
    $post->follows()->attach(\Auth::id(), ['created_at'=>Carbon::now()]);
    return back()->with('success', '关注成功');
}

// 评论接口
public function comment(Request $request, Post $post){
    $this->validate($request, [
        'content' => 'required|string|min:4|max:256'
    ]);
    $comment = $request->all();
    $comment['post_id'] = $post->id;
    $comment['user_id'] = \Auth::id();
    // observer有调用
    $post->comments()->create($comment);
    return back()->with('success', '评论成功');
}

FollowObserver类

<?php

namespace App\Observers;

use App\Models\Follow;

class FollowObserver
{
    /**
     * Handle the follow "created" event.
     *
     * @param  \App\Models\Follow  $follow
     * @return void
     */
    public function created(Follow $follow)
    {
        $post = $follow->post();
        // post关注数+1
        $post->increment('follow_count');
    }
}

CommentObserver

<?php

namespace App\Observers;

use App\Models\Comment;
use App\Models\Post;
use Carbon\Carbon;

class CommentObserver
{
    /**
     * Handle the comment "created" event.
     *
     * @param  \App\Models\Comment  $comment
     * @return void
     */
    public function created(Comment $comment)
    {
        $post = $comment->post;
        // post的评论+1
        $post->increment('comment_count');
        // post的活跃时间更行
        $post->update(['updated_at'=> Carbon::now()]);
    }
}

ObserverServiceProvider

<?php

namespace App\Providers;

use App\Models\Comment;
use App\Models\Follow;
use App\Models\Post;
use App\Observers\CommentObserver;
use App\Observers\FollowObserver;
use Illuminate\Support\ServiceProvider;

class ObserverServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap services.
     *
     * @return void
     */
    public function boot()
    {
        //
        Comment::observe(CommentObserver::class);
        Follow::observe(FollowObserver::class);
    }

    /**
     * Register services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
lji123123
最佳答案

通过create调用,最终调用Model的save()方法。在真正insert之前是调用了几个生命周期的事件的。

file
file

在看attach调用

file

file

直接insert之后入库了。并没有触发observe的事件。

observe原理可以参考:https://juejin.im/post/5c866289e51d453ce66...

4年前 评论
讨论数量: 1
lji123123

通过create调用,最终调用Model的save()方法。在真正insert之前是调用了几个生命周期的事件的。

file
file

在看attach调用

file

file

直接insert之后入库了。并没有触发observe的事件。

observe原理可以参考:https://juejin.im/post/5c866289e51d453ce66...

4年前 评论

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