Laravel hasMany with where

2019-03-09 18:33发布

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?

2条回答
祖国的老花朵
2楼-- · 2019-03-09 19:24

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:

class Photo extends Eloquent {

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

}

class Car extends Eloquent {

    public function photos()
    {
        return $this->morphMany('Photo', 'imageable');
    }

}

class Flat extends Eloquent {

    public function photos()
    {
        return $this->morphMany('Photo', 'imageable');
    }

}

class Shop extends Eloquent {

    public function photos()
    {
        return $this->morphMany('Photo', 'imageable');
    }

}

And you could access the photos for, let's say a given Flat, like this:

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

For this to work you'd also need to add 2 additional columns to your photos table:

imageable_id: integer  <-- This will be the ID of the model
imageable_type: string <-- This will be the model's class name (Car/Flat/Shop)
查看更多
beautiful°
3楼-- · 2019-03-09 19:27

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.

class Cars extends Eloquent
{
    function photos()
    {
        return $this->hasMany('Photo')->where('photos.type', '=', 'Cars');
    }
}
查看更多
登录 后发表回答