我应该在laravel中使用EAV模型吗? [英] Should I use a EAV model or not in laravel?

查看:119
本文介绍了我应该在laravel中使用EAV模型吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个应用程序,我的应用程序中大约有20个类别,每个类别都有一些自定义字段。因此,用户选择一个类别并填写自定义字段。之后,我需要将值存储在DB中。您能建议什么是最好的方法吗?另外,我还需要能够过滤此自定义字段-就像高级过滤器一样,性能也是关键。

I am building a app and I have in my app around 20 categories and each category has some custom fields. So a user picks a category and fills in the custom fields. After that I need to store the values in DB. Can you suggest what would be the best approach to do it. Also I need to be able to filter on this custom fields - like a advanced filter and a performance is a key too.

我应该为每个类别单独创建一个表格

Should I just make for each category a separate table with their custom fields in such case?

谢谢您的帮助

Dany

推荐答案

我可以想到两个选项。

1)创建一个名为JSON的字段类似于类别表中的属性。然后,基本上在其中存储键值数组。但是在查询属性时,这将带来一些挑战。我知道有很多解决方法,但是我从不需要它,所以我不知道。

1) Create a JSON field called something like attributes in your category table. And then store basically an array of Key Values in it. That will present some challenges when querying on attributes though. I know there are ways around it but i've never needed it so I do not know.

2)在数据库中创建一个Category Attributes表,内容如下

2) Create a Category Attributes table in your DB that goes something like this

cat_id - int
key - varchar
value - varchar
Composite Index Unique on [cat_id, key,value ]

然后在laravel中创建Category属性模型并定义hasmany关系,其中Category有很多类别属性

Then create a Category Attribute model in laravel and define a hasmany relationship where Category has many Category Attributes

然后查询您的类别将是这样的

then querying your categories would go something like this

$ category = Category :: whereHas('CategoryAttributes',function($ query){
$ query-> where('key','=','color');
$ query-> where('value','=','blue');
})-> get();

这篇关于我应该在laravel中使用EAV模型吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆