I have 3 tables, Cars, Flats and Shops. Each table has its photos. Photos is stored in database. I want to use only one table for photos, I don't want to create Photos table for each Cars, Flats and Shops.
Photos tables structe is like this;
| id | photo_url | type | destination_id |
------------------------------------------------------------
1 | http://example.com/1.jpg | Cars | 1 |
2 | http://example.com/2.jpg | Flats | 1 |
3 | http://example.com/3.jpg | Flats | 2 |
4 | http://example.com/4.jpg | Shops | 1 |
5 | http://example.com/3.jpg | Shops | 2 |
I need to define hasMany relationship with type in Shops, Flats and Cars model classes.
What is the correct way to do this?
You can make use of Eloquent's Polymorphic relationships. The example in the Laravel Documentation actually showcases setting up a common images table for multiple models, so that should point you in the right direction. In your case something your models would look something like this:
And you could access the photos for, let's say a given
Flat
, like this:For this to work you'd also need to add 2 additional columns to your
photos
table:You can treat the relationship objects kind of like queries, in that you can call query building functions with them. The example below should get you going in the right direction.