Eager Loading 的实现过程
打赏作者

liudong0763

听的我头都大了

liudong0763

Jelly, 我在看源代码的时候有个疑问,始终搞不懂,我在eloquent\model里面的 with方法可以 dd(relations),但是在 eloquent buider 里面的with方法中 dd(relations) 始终是空数组,这是为什么?

eloquent\model :
 /**
     * Begin querying a model with eager loading.
     *
     * @param  array|string  $relations
     * @return \Illuminate\Database\Eloquent\Builder|static
     */
    public static function with($relations)
    {
        if (is_string($relations)) {
            $relations = func_get_args();//['post']
        }
        // dd($relations);
        $instance = new static;
        // dd($instance->newQuery());
        return $instance->newQuery()->with($relations);
    }

eloquent\builder:

    /**
     * Set the relationships that should be eager loaded.
     *
     * @param  mixed  $relations
     * @return $this
     */
    public function with($relations)
    {
        dd($relations);
        if (is_string($relations)) {
            $relations = func_get_args();
        }
        
        $eagers = $this->parseWithRelations($relations);

        $this->eagerLoad = array_merge($this->eagerLoad, $eagers);

        return $this;
    }
Smile雨后21 回复 liudong0763

用 dump() 你就知道了

f4cklangzi 回复 liudong0763

因为这个with走了两遍呀,我调试的时候也是一脸懵逼,结果他要先走一遍模型里面定义的全局with

foxriver123 回复 liudong0763

注册全局作用域的时候,传入了一个不带有全局作用域的eloquentBuilder,在制造这个不带全局作用距的eloquentBuilder的时候调用了一次with方法,这个时候with还是空所以

laravel0304

提个建议, 录源码这类的视频最好把IDE的 nav bar 打开,能看到是哪个文件,要不然不蒙圈都难

JellyBool 回复 laravel0304

可以的,不过这个看命名空间多好。

laravel0304 回复 JellyBool

好是好,但是大部分片段都没在头部 -。-

JellyBool 回复 laravel0304

阔以,这个建议我接受了,后面会注意

weiguangnixia

好难啊 听蒙了

wtry

新手入门的我,一直不知道,用obj比array好在什么地方,反正我是晕的,但是我有很多方法可以解决这个问题,真不知道这样复杂又没有必要。。。。还这么多foreach,是不是也不见得速度会好点。。。

foxriver123 回复 wtry

如果返回的是array,后续对数据的处理就会捉襟见肘

f8988082

已解决


return $this->hasOne(Wallet::class, 'wallet_uid', 'user_id')->select('wallet_cash');

为什么返回null啊

foxriver123

可惜教主留我而去

zedtse

想请教下如果post里的内容需要transform的话要怎么操作?查不到相关资料。。

Flourishing

laravel的高度封装 确实刚开始很难理解