我得到了這兩張表,其中一張表有多個指向第二張表的外鍵。
桌子 rankings
---------------- -------------- ------ ----- --------- ----------------
| Field | Type | Null | Key | Default | Extra |
---------------- -------------- ------ ----- --------- ----------------
| id | bigint(20) | NO | PRI | NULL | auto_increment |
| search_text | varchar(255) | YES | MUL | NULL | |
| first_item_id | bigint(20) | YES | MUL | NULL | |
| second_item_id | bigint(20) | YES | MUL | NULL | |
| third_item_id | bigint(20) | YES | MUL | NULL | |
| forth_item_id | bigint(20) | YES | MUL | NULL | |
---------------- -------------- ------ ----- --------- ----------------
桌子 items
--------------------------- -------------- ------ ----- --------- ----------------
| Field | Type | Null | Key | Default | Extra |
--------------------------- -------------- ------ ----- --------- ----------------
| id | bigint(20) | NO | PRI | NULL | auto_increment |
| item_code | varchar(255) | YES | MUL | NULL | |
---------------- -------------- ------ ----- --------- ---------------------------
樣本資料 rankings
---- ------------- ------- -------- ------- -------
| id | search_text | first | second | third | forth |
---- ------------- ------- -------- ------- -------
| 1 | test 1 | 1 | 2 | 3 | 4 |
| 2 | test 2 | 1 | 2 | 3 | 4 |
| 3 | test 3 | 1 | 2 | 3 | 4 |
| 4 | test 4 | 1 | 2 | 3 | 4 |
---- ------------- ------- -------- ------- -------
樣本資料 items
-------- ------------
| id | item_code |
-------- ------------
| 1 | 125659 |
| 2 | 125660 |
| 3 | 125661 |
| 4 | 125662 |
-------- ------------
目前我正在按如下方式檢索排名資料:
@rankings = Admin::Ranking.all
預期資料
---- ------------- ------- -------- ------- -------
| id | search_text | first | second | third | forth |
---- ------------- ------- -------- ------- -------
| 1 | test 1 | 125659| 125660 | 125661| 125662|
| 2 | test 2 | 125659| 125660 | 125661| 125662|
| 3 | test 3 | 125659| 125660 | 125661| 125662|
| 4 | test 4 | 125659| 125660 | 125661| 125662|
---- ------------- ------- -------- ------- -------
檢索預期資料的 SQL 查詢:
SELECT
r.id,
r.search_text,
i1.item_code AS first,
i2.item_code AS second,
i3.item_code AS third,
i4.item_code AS forth
FROM rankings r
LEFT JOIN items i1 ON i1.id = r.first_item_id
LEFT JOIN items i2 ON i2.id = r.second_item_id
LEFT JOIN items i3 ON i3.id = r.third_item_id
LEFT JOIN items i4 ON i4.id = r.forth_item_id
ORDER BY r.id;
模型類如下:
items-> Item,
rankings->Ranking
關于如何使用 Rails 以預期格式檢索排名資料的任何建議ActiveRecord?
uj5u.com熱心網友回復:
為每個外鍵創建一個單獨的關聯。
class Ranking < ApplicationRecord
belongs_to :first_item, class_name: 'Item'
belongs_to :second_item, class_name: 'Item'
belongs_to :third_item, class_name: 'Item'
belongs_to :forth_item, class_name: 'Item'
end
然后您可以只包含所有這些并根據需要進行查詢。
rankings = Ranking.all.includes(:first_item, :second_item, :third_item, :forth_item)
rankings.each do |ranking|
ranking.first_item.item_code # example
end
這是 ActiveRecord 的方式。如果你只想得到item_code-s 而沒有別的,你可以.select改為。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/315235.html
