如何对多对多数据表 followers 使用模型观察事件?$this->followings ()->sync ($user_ids, false) 无法触发 created?

通过user_user构建了数据表followers,models里也有follower,但是对Follower使用Observer事件无效。

<?php

namespace App\Observers;

use App\Models\Follower;

// creating, created, updating, updated, saving,
// saved,  deleting, deleted, restoring, restored

class FollowerObserver
{
    public function created(Follower $follower)
    {
        $user = $follower->user;
        $user->increment('follower_count', 1);

        $user = $follower->follower_user;
        $user->increment('following_count', 1);
    }

    public function deleted(Follower $follower)
    {
        $user = $follower->user;
        $user->increment('follower_count', -1);

        $user = $follower->follower_user;
        $user->increment('following_count', -1);
    }

}
    public function follow($user_ids)
    {
        if (!is_array($user_ids)) {
            $user_ids = compact('user_ids');
        }
        $this->followings()->sync($user_ids, false);
    }

    public function unfollow($user_ids)
    {
        if (!is_array($user_ids)) {
            $user_ids = compact('user_ids');
        }
        $this->followings()->detach($user_ids);
    }
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
讨论数量: 2
liyu001989

多对多的关系表,不会触发事件

6年前 评论

@liyu001989
$this->followings()->sync($user_ids, false);
这句给中间表附加字段的应该如何理解?

$user_ids只有一个值啊,为何user_id和follower_id都被填充了

6年前 评论

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