簡體   English   中英

當返回表與 model 導軌不匹配時,我如何從多個表中獲取 select

[英]How do I select from multiple tables when the return table doesn't match the model rails

我有 2 張桌子

t1:

id | object_id
---+----------
1  | 11
2  | 12
3  | 13

t2:

id | object_id
---+----------
21  | 11
22  | 12
23  | 13

我想要下表:

t1_id | t2_id |object_id | 
------+-------+-----------
1     | 21    | 11
2     | 22    | 12
3     | 23    | 13

SQL 相當簡單:

select t1.id as t1_id, t2.id as t2_id, t1.object_id from t1 left join t2 on t1.object_id = t2.object_id

我的目標是在 Rails 中獲得如下所示的內容:

[
  {
    t1_id: 1,
    t2_id: 21,
    object_id: 11
  },
  {
    t1_id: 2,
    t2_id: 22,
    object_id: 12
  },
  {
    t1_id: 3,
    t2_id: 23,
    object_id: 13
  },
]

但我不確定我如何用我的模型做到這一點。 這就是我所擁有的,但它忽略了 t2_id 因為我認為它不適合 t1 model

T1.select("t1.id as t1_id, t1.object_id, t2.id as t2_id")
  .joins("LEFT OUTER JOIN t2 ON t1.object_id = t2.object_id")

當你這樣說時:

q = T1.select('...')

q中的 model 實例將具有與您選擇的內容相匹配的屬性,無論T1具有什么屬性。 所以,在你的情況下:

q = T1.select("t1.id as t1_id, t1.object_id, t2.id as t2_id")...

你可以這樣說:

m = q.first
m.t1_id
m.object_id
m.t2_id

通常,您從查詢中獲得的模型的屬性與select所說的相匹配,而不是模型表所說的; 但是select通常是一個隱式select('table_name.*')所以屬性和列名默認排列。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM