使用 sync 和 detach 来做关注和取消关注, 怎么触发 Follower 的 created 事件? 求教

如题

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 开发相关的进阶知识。
ibucoin
最佳答案

@LiJie123 可以的,在多对多关系下添加->withTimeStamps();

5年前 评论
讨论数量: 5

恕我没明白你的问题和需求 :joy:

5年前 评论

@雪风 首先感谢回答, 我的本意是想实现"A用户关注B用户时, B用户收到一个通知", 想利用Follower模型created事件来实现. 可惜教程中关注用户是使用 sync 方法, 不会触发Follower模型的created事件.
所以想知道有什么解决方法?
下面是我简陋的解决方法, 没有使用到事件! 不过还是想知道原题目的解决方法. 感谢~.~

public function follow($user_ids)
    {
        if (!is_array($user_ids)) {
            $user_ids = compact('user_ids');
        }
        $changes = $this->followings()->sync($user_ids, false);
        $users = User::find($changes['attached'])->all();
        foreach ($users as $user) {
            $follower = Follower::where(['user_id' => $user->id, 'follower_id' => $this->id])->first();
            $user->notify(new UserFollowed($follower));
        }
    }
5年前 评论

恕我没明白你的问题和需求 :joy:

5年前 评论

@雪风 @Achais @瓜皮 sync 和 detach 好像不会在数据库表 followers 中存储 create_at 和 update_at 字段

5年前 评论
ibucoin

@LiJie123 可以的,在多对多关系下添加->withTimeStamps();

5年前 评论

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