0
我試圖從關聯examples中獲得關聯工作正常的關聯之一,並且它似乎沒有正確設置連接表。在這個例子中,我們有一個叫Person的模型,然後是一個Person的孩子的多對多自我引用。代碼:續集多對多自引用
var Sequelize = require('sequelize');
var sequelize = new Sequelize('postgres://[email protected]/database_bug');
var Person = sequelize.define('Person', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
name: {
type: Sequelize.STRING,
allowNull: false
}
});
Person.belongsToMany(Person, { as: 'Children', through: 'PersonChildren' });
Person.sequelize.sync({force:true}).then(function() {
Person.build({ name: 'John Doe' }).save().then(function(father) {
Person.build({ name: 'Jane Doe' }).save().then(function(daughter) {
father.addChild(daughter);
});
});
});
但是,當我看着我的表在Postgres的我覺得自己像一個列上缺少自動生成的連接表。
List of relations
Schema | Name | Type | Owner
--------+----------------+----------+-------
public | People | table | root
public | People_id_seq | sequence | root
public | PersonChildren | table | root
Table "public.People"
Column | Type | Modifiers
-----------+--------------------------+-------------------------------------------------------
id | integer | not null default nextval('"People_id_seq"'::regclass)
name | character varying(255) | not null
createdAt | timestamp with time zone | not null
updatedAt | timestamp with time zone | not null
Indexes:
"People_pkey" PRIMARY KEY, btree (id)
Referenced by:
TABLE ""PersonChildren"" CONSTRAINT "PersonChildren_PersonId_fkey" FOREIGN KEY ("PersonId") REFERENCES "People"(id)
Table "public.PersonChildren"
Column | Type | Modifiers
-----------+--------------------------+-----------
createdAt | timestamp with time zone | not null
updatedAt | timestamp with time zone | not null
PersonId | integer | not null
Indexes:
"PersonChildren_pkey" PRIMARY KEY, btree ("PersonId")
Foreign-key constraints:
"PersonChildren_PersonId_fkey" FOREIGN KEY ("PersonId") REFERENCES "People"(id)
PersonChildren
需要一個叫做沿着這些線路ChildId
或某事的人鏈接到其子列。
People表:
database_bug=# SELECT * FROM "People";
id | name | createdAt | updatedAt
----+----------+----------------------------+----------------------------
1 | John Doe | 2015-02-06 09:36:44.975-08 | 2015-02-06 09:36:44.975-08
2 | Jane Doe | 2015-02-06 09:36:44.985-08 | 2015-02-06 09:36:44.985-08
怪異,我仍然選擇以確保daughter
加入爲孩子father
:
database_bug=# SELECT * from "PersonChildren";
createdAt | updatedAt | PersonId
----------------------------+----------------------------+----------
2015-02-06 09:36:44.997-08 | 2015-02-06 09:36:44.997-08 | 2
但PERSONID是2,而不是1 father
應該添加daughter
,而不是相反。
任何想法如何讓這個協會工作?
此問題已在Sequelize中修復。他們現在建議您在創建多對多自引用時使用'.belongsToMany'。 – 2015-03-05 17:10:23
在創建多對多自引用時,您是否有belongsToMany的示例? – 2015-06-30 22:07:43