Friday 15 July 2011

orm - Laravel hasMany with where -



orm - Laravel hasMany with where -

i have 3 tables, cars, flats , shops. each table has photos. photos stored in database. want utilize 1 table photos, don't want create photos table each cars, flats , shops.

photos tables structe 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 define hasmany relationship type in shops, flats , cars model classes.

what right way this?

you can create utilize of eloquent's polymorphic relationships. illustration in laravel documentation showcases setting mutual images table multiple models, should point in right direction. in case models this:

class photo extends eloquent { public function imageable() { homecoming $this->morphto(); } } class auto extends eloquent { public function photos() { homecoming $this->morphmany('photo', 'imageable'); } } class flat extends eloquent { public function photos() { homecoming $this->morphmany('photo', 'imageable'); } } class shop extends eloquent { public function photos() { homecoming $this->morphmany('photo', 'imageable'); } }

and access photos for, let's given flat, this:

flat::find($id)->photos;

for work you'd need add together 2 additional columns photos table:

imageable_id: integer <-- id of model imageable_type: string <-- model's class name (car/flat/shop)

laravel orm laravel-4 eloquent

No comments:

Post a Comment