iT邦幫忙

0

ORM中如何做到多對多關聯的?

想請問在ORM的框架中,是怎麼做one to many,many to many這些關聯轉成List的?

ex: 假設我有這樣的資料
https://ithelp.ithome.com.tw/upload/images/20210721/20138375kZxAC0kqh7.png

我會希望轉成物件後會變成像這樣:

class Teacher{
  
  private String id;

  private String name;

  private String age;

  private List<Student> students;

}

class Student{
  
    private String name;

}

我知道許多ORM框架可以做到,但現在遇到的環境無法使用ORM,必須手動做這部分,
有前輩可以指點一下嗎,不知道怎麼下手比較好

看更多先前的討論...收起先前的討論...
淺水員 iT邦大師 6 級 ‧ 2021-07-21 16:01:50 檢舉
那個 age 是 teacher 的還是 student 的?
shawnswu iT邦新手 5 級 ‧ 2021-07-21 16:12:26 檢舉
Teacher的 抱歉資料有誤 修改了
froce iT邦大師 1 級 ‧ 2021-07-21 19:00:11 檢舉
就多一張中繼表紀錄兩者的關係啊。
shawnswu iT邦新手 5 級 ‧ 2021-07-21 21:57:42 檢舉
有相關資料嗎?這樣講不是很理解
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

0
froce
iT邦大師 1 級 ‧ 2021-07-21 19:07:11

這是python的code
orm

class Author(models.Model):
    name = models.CharField(max_length=20)


class Book(models.Model):
    name = models.CharField(max_length=20)
    author = models.ManyToManyField("Author")

會產生3張表
book、author、book_author
book

id|name
1 |java
2 |python

author

id|name
1 |aaa
2 |bbb

book_author

book_id|author_id
1      |1
1      |2
2      |2
看更多先前的回應...收起先前的回應...
shawnswu iT邦新手 5 級 ‧ 2021-07-21 21:59:05 檢舉

那有中繼表(book_author)後,程式端是要把這個book_author的資料抓回來 然後在程式端處理這些資料 是嗎?

shawnswu iT邦新手 5 級 ‧ 2021-07-21 22:44:19 檢舉

程式端那段不知道怎麼轉會比較好

froce iT邦大師 1 級 ‧ 2021-07-22 09:47:58 檢舉

假設我要選取java這本書的作者,從book_author去延伸:

select book.name as book_name, author.name as author
from book_author
join author on author_id = author.id
join book on book_id = book.id
where book_author.book_id = (
  select id
  from book
  where book.name = 'java'
) 

另外還有個作弊辦法,在其他地方寫orm去生成raw sql然後直接貼到程式裡。

froce iT邦大師 1 級 ‧ 2021-07-22 10:22:28 檢舉

然後1對多就直接join或子查詢就好了,比較沒那麼麻煩,要多一張表。

我要發表回答

立即登入回答