Ad

Using Other Column As Identifier In Polymorphic Relationship

- 1 answer

I am using Eloquent on my project and I am currently facing a problem with regards to polymorphic relations. What I would like to do is to specify another column instead of the primary key in morphing relationship such that:

Products

  • id
  • product_number
  • description

User

  • id
  • username

Photos

  • id
  • path
  • imageable_id
  • imageable_type

In this scenario, I would like to create a relation with both the products and the users table, but in the product relationship, instead of putting the ID as the relationship identifier, I would like to put the product_number because of some reasons. Is it possible as of version 5.1?

Thanks,

Jan

Ad

Answer

It is possible by specifying the local key like so:

return $this->morphMany('App\Photos', 'imageable', null, null, 'product_number' );
Ad
source: stackoverflow.com
Ad