2017-07-28 110 views
-1

我在多對多關係兩個表:如何填充中間表?

表分子:

id | main_name | others … 
--- | --------- | ------ 
1 | caféine | others … 

表jsonTextMining:

id | title | molecule_name      | others … 
---|------- |-------------------------------------|------ 
1 | title1 | colchicine, cellulose, acid, caféine| others … 

和1箇中間表:

表json_text_mining_molecule(這是個例我沒有成功,填補吧):

json_text_mining_id  | molecule_id 
------------------------ | --------------- 
1      | corresponding molecule id's 
1      | corresponding molecule id's 
2      | corresponding molecule id's 

我的問題是,在molecule_namejsonTextMining一個字符串,我需要什麼之前將它們分開。

我嘗試這樣做:

$molecules = explode (', ', $jsonTextMining→getMoleculeName()); 
foreach ($molecules as $molecule) { 
$jsonTextMining->setMolecule($molecule); 
} 
$em->persist($jsonTextMining); 
$em->flush; 

但我想我應該循環上jsonTexMining過併成爲honnest我不知道往哪裏放的這部分代碼。它是在一個隨機頁面上,代碼將執行,我應該做一個按鈕?

我確切地知道如何填寫表ID的時候有一個一對多的關係,我用sql這樣的:

UPDATE table1 SET id_relation1 = table2.id 
FROM table2 
WHERE table1.main_name = table2.main_name 

但這個代碼只填寫一列與ID和總有串的問題。是否真的有辦法讓這些id鏈接起來,因此每個分子都會有幾個jsonTextMining?

select id, regexp_split_to_table(molecule_name,', ') as m_name from jsonTextMining 

這會給你的ID和姓名的一個表:

+0

請@Magnus告訴我如何編輯我的表,我試圖做同樣的代碼4位,但它沒有工作 – Gy0m

+0

這是因爲你在前面有字符'-'你的r表名。 '-'將被解析爲一個列表,並且不能像列表中那樣擁有代碼塊。 –

+1

哦,太好了,所以我明白你爲什麼要把表名放在粗體thx中我會在下一次做 – Gy0m

回答

0

可以使用regexp_split函數首先拆分字符串

id | name 
----+------------ 
    1 | acid 
    1 | caffeine 
    1 | cellulose 
    1 | colchicine 

接下來,你可以從上面的讀取,匹配命名爲分子表中的ID並聚合ID。全部放在一起會導致這樣的:

select s.id, string_agg(m.id::text, ', ') 
from (select id, regexp_split_to_table(molecule_name,', ') as m_name 
    from jsonTextMining) as s, molecules m 
where m.main_name = s.m_name group by s.id; 

其中給出這樣的結果:

id | string_agg 
----+------------ 
    1 | 4, 1, 3, 2 
(1 row) 

如果你不想彙總的結果,並顯示它們每分子一行則剛剛擺脫string_agg的和GROUP BY:

select s.id, m.id 
from (select id, regexp_split_to_table(molecule_name,', ') as m_name 
    from jsonTextMining) as s, molecules m 
where m.main_name = s.m_name; 
+0

好,我怎麼能得到這個結果在多行? – Gy0m

+0

@ Gy0m上面的查詢適用於任意數量的行。你還有問題嗎? –

+0

我編輯了答案,以顯示如果您希望每個分子ID有一行,該怎麼辦。 –