【发布时间】:2018-03-28 16:37:22
【问题描述】:
当他们是供应商时,如何创建视图(producer_view 和 retailer_view)显示每个交易 SUM( unit_price * quantity ) 的总金额 和 客户 ?
producer_view
+------+-------------------+-----------------+
| name | as_supplier_total | as_client_total |
+------+-------------------+-----------------+
| foo | 144 | 9 |
| bar | 9 | 264 |
+------+-------------------+-----------------+
retailer_view
+------+-------------------+-----------------+
| name | as_supplier_total | as_client_total |
+------+-------------------+-----------------+
| baz | 16 | 125 |
| qux | 245 | 16 |
+------+-------------------+-----------------+
我的两个困难是:
每个事务的
supplier_id和client_id存储在两个多态关联中,其中supplier_type和client_type可以是@ 987654329@或App\Retailer。每个事务的
unit_price和quantity都存储在一个子表中。
两个父表是:
Producer
+----+------+
| id | name |
+----+------+
| 1 | foo |
| 2 | bar |
+----+------+
Retailer
+----+------+
| id | name |
+----+------+
| 1 | baz |
| 2 | qux |
+----+------+
在交易中,生产者和零售商都可以是供应商或客户强>。
Transaction
+----+---------+-------------+---------------+-----------+--------------+
| id | product | supplier_id | supplier_type | client_id | client_type |
+----+---------+-------------+---------------+-----------+--------------+
| 1 | a | 1 | App\Producer | 1 | App\Retailer |
| 2 | b | 2 | App\Retailer | 1 | App\Retailer |
| 3 | c | 1 | App\Producer | 2 | App\Producer |
| 4 | d | 2 | App\Retailer | 2 | App\Producer |
+----+---------+-------------+---------------+-----------+--------------+
每个交易的详细信息都记录在item表中:
Item
+----+----------------+------------+----------+
| id | transaction_id | unit_price | quantity |
+----+----------------+------------+----------+
| 1 | 1 | 10 | 1 |
| 2 | 1 | 20 | 1 |
| 3 | 2 | 30 | 1 |
| 4 | 2 | 40 | 1 |
| 5 | 3 | 50 | 1 |
| 6 | 3 | 60 | 1 |
| 7 | 4 | 70 | 1 |
| 8 | 4 | 80 | 1 |
| 9 | 5 | 2 | 2 |
| 10 | 6 | 3 | 3 |
| 11 | 7 | 4 | 4 |
| 12 | 8 | 5 | 5 |
+----+----------------+------------+----------+
来自以下经过验证的答案的 SQLFiddle:
【问题讨论】:
标签: mysql views polymorphic-associations