Laravel hasMany 与 where
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26433885/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel hasMany with where
提问by fobus
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.
我有 3 张桌子,汽车、公寓和商店。每张桌子都有照片。照片存储在数据库中。我只想使用一张照片表,我不想为每个汽车、公寓和商店创建照片表。
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.
我需要在 Shops、Flats 和 Cars 模型类中定义 hasMany 与类型的关系。
What is the correct way to do this?
这样做的正确方法是什么?
采纳答案by Bogdan
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:
您可以利用 Eloquent 的多态关系。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');
}
}
And you could access the photos for, let's say a given Flat
, like this:
你可以访问照片,比如给定的Flat
,像这样:
Flat::find($id)->photos;
For this to work you'd also need to add 2 additional columns to your photos
table:
为此,您还需要向photos
表中添加 2 个额外的列:
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)
回答by Logan Bailey
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');
}
}