这里为什么判断是否为数组 is_array ($user_ids?

为什么这个要这么写?

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

而不是直接:

    public function follow($user_ids)
    {
        $this->followings()->sync($user_ids, false);
    }

1,请问下这里为什么要使用 “is_array ($user_ids” 判断 $user_ids 是不是数组?,用点击关注 以及取消关注难道会传入数组吗? 一个用户关注一个用户,不是批量关注。

>>> $user->followings()->sync(1, false)

取消关注

>>> $user->followings()->detach(1)

无论关注以及取消都不需要传入数组啊,为什么要判断是否是数组,?

《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
最佳答案

看源码是

     /**
     * Sync the intermediate tables with a list of IDs or collection of models.
     *
     * @param  \Illuminate\Support\Collection|\Illuminate\Database\Eloquent\Model|array  $ids
     * @param  bool   $detaching
     * @return array
     */
    public function sync($ids, $detaching = true)
    {
4年前 评论
李小明 (楼主) 4年前
讨论数量: 3

这里是, 如果传入的值 不是数组, 那给他转成数组 ,

4年前 评论
李小明 (楼主) 4年前

你也可以使用 sync 方法构建多对多关联。sync 方法接收一个 ID 数组以替换中间表的记录。中间表记录中,所有未在 ID 数组中的记录都将会被移除。所以该操作结束后,只有给出数组的 ID 会被保留在中间表中:

文档是这么写

4年前 评论

看源码是

     /**
     * Sync the intermediate tables with a list of IDs or collection of models.
     *
     * @param  \Illuminate\Support\Collection|\Illuminate\Database\Eloquent\Model|array  $ids
     * @param  bool   $detaching
     * @return array
     */
    public function sync($ids, $detaching = true)
    {
4年前 评论
李小明 (楼主) 4年前

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