2014-10-17 100 views
17

我有3张桌子,汽车,公寓和商店。每张桌子都有它的照片。照片存储在数据库中。我只想使用一张桌子照片,我不想为每个汽车,公寓和商店创建照片列表。Laravel hasMany with Where

照片表structe是这样的;

| 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   | 

我需要在Shops,Flats和Cars模型类中定义与类型的许多关系。

这样做的正确方法是什么?

回答

13

您可以使用Eloquent的Polymorphic relationships。 Laravel文档中的示例实际上展示了为多个模型设置一个通用图像表,以便您指出正确的方向。在你万一你的模型会是这个样子:

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'); 
    } 

} 

而且你可以访问照片,比方说,一个给定的Flat,像这样:

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

对于这个工作,你会还需要2个额外的列添加到您的photos表:

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) 
+2

Spasibo bratan! – fobus 2014-10-17 22:24:22

40

您可以使用类似于查询的关系对象类型,因为您可以使用它们调用查询构建函数。下面的例子应该让你朝着正确的方向前进。

class Cars extends Eloquent 
{ 
    function photos() 
    { 
     return $this->hasMany('Photo')->where('photos.type', '=', 'Cars'); 
    } 
} 
+0

非常感谢,我需要调用'令::与( '的OrderItems') - >在哪里( 'orderItems.type',1) - >与('orderItems.o rderItemOptions','orderItems.orderMenuItems') - > first()',并且作用域不会那样工作 – cnlevy 2015-11-05 21:20:30