Thanh Dao
Thanh Dao

Reputation: 1260

How to retrieve data from Polymorphic Relations with Laravel 5.5?

I'm new in Laravel. I'm developing a demo with Polymorphic Relations follow the documentation

I set up 3 tables:

--Users
  --id
  --username
--Posts
  --id
  --summary
  --published
--Images
  --id
  --link
  --alt
  --image_id
  --image_type

App\Models\Users

public function scopeWithImages()
{
    return static::with('images')->get();
}

public function images()
{
    return $this->morphMany('App\Models\Images', 'image');
}

App\Models\Posts

public function scopeWithImages()
{
    return static::with('images')->get();
}

public function images()
{
    return $this->morphMany('App\Models\Images', 'image');
}

App\Models\Images

public function scopeWithUsers ()
{
    return static::with('users')->get();
}

public function users()
{
    return $this->morphedByMany('App\Models\Users', 'image');
}

public function posts()
{
    return $this->morphedByMany('App\Models\Posts', 'image');
}

I got Images collection by calling Users and Posts model easily.
How I got Users and Posts collection from Images model? I got error Unknown column 'images.images_id'

Upvotes: 5

Views: 7569

Answers (2)

Hamidreza Ghanbari
Hamidreza Ghanbari

Reputation: 307

first, your idea is incorrect because the relation between images and users and post is one to many polymorphic, in this scenario you just need to write $user->images to retrieve images that belong to the user or write$post->images to get post images.

// but in your code you want each user or post have many images that might be for user or post or all together in your senario you $post = Post::find(1); dd($post->images) to retrive images of one post

hope this work for you

Upvotes: 1

Chamara Abeysekara
Chamara Abeysekara

Reputation: 1322

your relationship method are wrong it should be like this

App\Models\Users

public function image()
{
    return $this->morphMany('App\Models\Images', 'image');
}

App\Models\Posts

public function image()
{
    return $this->morphMany('App\Models\Images', 'image');
}

App\Models\Images

public function image()
{
    return $this->morphTo();
}

the method name should be column name before the underscore image_id == image()

prefer - https://laravel.com/docs/5.5/eloquent-relationships#polymorphic-relations

Upvotes: 4

Related Questions