简体   繁体   中英

Laravel 5.2 - Eager load distant model in Polymorphic relation

I have a like system built with Polymorphic relations. I'd like to eager load the model of the likeable_type when retrieving the Likes. What do I need to do? I tried to add

protected $with = ['Post'];

or

protected $with = ['App\Post'];

to my Like model but all I get is:

Call to undefined method Illuminate\\Database\\Query\\Builder::Post()

Like model:

class Like extends Model
{
    use SoftDeletes;

    protected $table = 'likeables';

    protected $fillable = [
        'user_id',
        'likeable_id',
        'likeable_type',
    ];


    /**
     * Get all of the owning likeable models.
     */
    public function likeable()
    {
        return $this->morphTo();
    }

}

Post Model:

class Post extends Model
{

    protected $fillable = [

        'picture',
        'description'

    ];


    /**
     *
     * a post belongs to one user
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function user(){

        return $this->belongsTo('App\User');

    }


    /**
     *
     * a post has many comments
     *
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
     */
    public function comments()
    {
        return $this->hasMany('App\Comment');
    }


    /**
     * Get all of the post's likes.
     */
    public function likes()
    {        

        return $this->morphMany('App\Like', 'likeable');
    }


    /**
     *
     * Simple Like System checks if liked
     *
     * @return bool
     */
    public function getIsLikedAttribute()
    {
        $like = $this->likes()->whereUserId(Auth::id())->first();
        return (!is_null($like)) ? true : false;
    }


}

I solved this issue by renaming the table from 'likeables' to 'likes'.

protected $table = 'likeables'; -> protected $table = 'likes';

Now I can retrieve the distant relation when retrieving the like like this:

$post = Post::find(6);

dd ($post->likes()->with('likeable')->get());

or I can retrieve the liked entity like this:

$like = Like::find(1);

$likeable = $like->likeable;

dd($likeable);

before renaming the table the result was Null.. I still have to understand how to retrieve all the entities liked by a User.

Illuminate\\Database\\Query\\Builder::Post()

You have a problem about post.

You can take datas like this with "firstOrFailed()":

$data=table_name::where('$id','like',$id)->firstOrFailed();

Or "get()" method. (This changes with releations.)

This is the tutorial about polimorphic releations. https://laravel.com/docs/5.3/eloquent-relationships#polymorphic-relations

If you can't solve the problem, please give more information like controller, view page and migration.

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