Laravel Eloquent关系取决于项目的类型

时间:2017-04-05 22:28:40

标签: laravel eloquent laravel-eloquent

我有模型Product,它有两种类型:LampsBulbs。一盏灯具有一组与灯泡不同的属性,因此我有另外两个模型LampBulb代表一组属性。在这种情况下,我应该实现从产品到属性模型的哪种关系?

我一直在尝试一对一的关系,但在我的情况下,第二个“一”与产品的类型不同。

我一直在想 EAV 模式,但我现在不想在我的架构中加入大量的连接,因为我不需要超过这两种类型的项目。

你会建议什么?

UPD1:以下是表格(简化):

mysql> show columns from products;
+-------------+--------------+------+-----+---------+----------------+
| Field       | Type         | Null | Key | Default | Extra          |
+-------------+--------------+------+-----+---------+----------------+
| id          | int(11)      | NO   | PRI | NULL    | auto_increment |
| name        | varchar(127) | NO   |     | NULL    |                |
| price       | double       | NO   |     | NULL    |                |
| old_price   | double       | NO   |     | NULL    |                |
| category_id | int(11)      | NO   |     | NULL    |                |
+-------------+--------------+------+-----+---------+----------------+
5 rows in set (0.00 sec)

mysql> show columns from lamps;
+------------+---------+------+-----+---------+----------------+
| Field      | Type    | Null | Key | Default | Extra          |
+------------+---------+------+-----+---------+----------------+
| id         | int(11) | NO   | PRI | NULL    | auto_increment |
| product_id | int(11) | NO   |     | NULL    |                |
| width      | int(11) | NO   |     | NULL    |                |
| height     | int(11) | NO   |     | NULL    |                |
| length     | int(11) | NO   |     | NULL    |                |
| weight     | int(11) | NO   |     | NULL    |                |
+------------+---------+------+-----+---------+----------------+
7 rows in set (0.00 sec)

mysql> show columns from bulbs;
+------------+---------+------+-----+---------+----------------+
| Field      | Type    | Null | Key | Default | Extra          |
+------------+---------+------+-----+---------+----------------+
| id         | int(11) | NO   | PRI | NULL    | auto_increment |
| product_id | int(11) | NO   |     | NULL    |                |
| voltage    | int(11) | NO   |     | NULL    |                |
| power      | int(11) | NO   |     | NULL    |                |
| base       | int(11) | NO   |     | NULL    |                |
| type       | int(11) | NO   |     | NULL    |                |
+------------+---------+------+-----+---------+----------------+
6 rows in set (0.00 sec)

UPD2:据我所知,我可以在products表中使用两个外键,并为每条记录只设置其中一个,但对于这种情况,是否有更优雅的方案?

0 个答案:

没有答案
相关问题