简体   繁体   中英

Eager loading on polymorphic relations

class Admin {
    public function user()
    {
        return $this->morphOne('App\Models\User', 'humanable');
    }

    public function master()
    {
        return $this->hasOne('App\Models\Master');
    }
}


class Master {
    public function admin()
    {
        return $this->hasOne('App\Models\Admin');
    }
}

class User {
    public function humanable()
    {
        return $this->morphTo();
    }

    public function images()
    {
        return $this->hasOne('\App\Models\Image');
    }
}

class Image {
    public function user()
    {
        return $this->belongsTo('\App\Models\User');
    }
}

Now if I dump this:

return \App\Models\Admin::where('id',1)->with(array('user.images','master'))->first();

I get the perfect result one master, one user and one image record.

But if I do this

return $user = \App\Models\User::where('id',1)->with(array('humanable','humanable.master'))->first();

I only get one Admin record, the query get * from masters doesn't even run.

Any idea what I'm doing wrong, I'm sure this is possible.

If I remember correctly Laravel has lots of pitfall. You can try to use the protected $with var in Admin model instead of query builder with function.

class Admin {
    protected $with = ['master'];

    public function user() {
        return $this->morphOne('App\Models\User', 'humanable');
    }

    public function master() {
        return $this->hasOne('App\Models\Master');
    }
}

In query builder, only need to include humanable . Now you should see master inside the humanable object.

return $user = \App\Models\User::where('id',1)->with('humanable')->first();

Hope this help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM