无法使用Sequelize在Schema(postgresql)中关联模型

时间:2014-08-29 09:46:38

标签: javascript node.js orm sequelize.js

我正在尝试使用Sequelize(1.7)和Postgresql(9.3)并尝试使用模式。我在数据库外部创建了模式,但在我的模型中使用它们。当我试图做模型关联时,Sequelize抱怨这种关系不存在。当我重新定义模型以使用PostgreSQL的默认“公共”模式时,它可以正常工作。

以下是测试用例的模型定义和代码

var Promise =   require("bluebird");
var Sequelize = require("sequelize");
var _ = require('lodash-node');

var schemaName ="test_schema";
var sequelize = new Sequelize( c.database,c.username,
    c.password,{dialect :'postgres', port:'5432',schema:schemaName});

var User =sequelize.define('User',{
id:{ type: Sequelize.INTEGER,primaryKey:true, autoIncrement:true},
name:{type:Sequelize.TEXT,allowNull:false},
nick_name:{type:Sequelize.TEXT,allowNull:true},
date_of_joining:{type:Sequelize.DATE,allowNull:false,defaultValue:Sequelize.NOW}

},
{
    tableName:"user",
    underscored:true,
    timestamps:false

}
);

var Task = sequelize.define( 'Task',
{
    id:{ type: Sequelize.INTEGER,primaryKey:true, autoIncrement:true},
    name:{type:Sequelize.TEXT,allowNull:false},
    begin_time:{type:Sequelize.DATE,allowNull:false,defaultValue:Sequelize.NOW},
    end_time:{type:Sequelize.DATE,allowNull:true}
},
{
    tableName:"task",
    underscored:true,
    timestamps:false

}

);

User.schema(schemaName);
Task.schema(schemaName);

User.hasMany( Task, {as:"Tasks"});

sequelize.sync( {force:true}, {logging:console.log})
.then( function( args ){

var users =[
    {name:"Abraham Milbard"},
    {name:"Jimmy Quake"},
    {name:"John Amayo"}
];
var tasks =[
    {name:"Bring 100 apples by today evening"},
    {name:"Do the dishes"},
    {name:"Watch soap and weep"},
    {name:"Bitch about your miserable life"}
];

User.create( users[0])
    .success( function( usr ){
        var chainer = new Sequelize.Utils.QueryChainer;
        var t1 = Task.build( tasks[0 ]),
            t2 = Task.build( tasks[1]);
        chainer.add(t1.save() );
        chainer.add(t2.save() );
        chainer.runSerially({ skipOnError:true})
            .success( function( results ){
                var tsk1 = results[0];
                var tsk2 = results[1];
                usr.setTasks([tsk1,tsk2]).success( function(assocTasks){

                });
            }).error( function( err ){
                console.log("Could not add tasks to user"+err);
            });

    }).error( function( err ){
        console.log("Could not create user ");
    });

});

如果执行此代码,则报告的错误为:

error: relation "task" does not exist

生成的查询是:

Executing (default): SELECT * FROM "test_schema"."task" WHERE "test_schema"."task"."user_id"=1;
Executing (default): UPDATE "task" SET "user_id"=1 WHERE "id" IN (1,2) RETURNING *

可以清楚地看到UPDATE语句失败,因为缺少模式前缀“test_schema”。换句话说,如果该工具发出以下查询:

 UPDATE "test_schema"."task" SET "user_id"=1 WHERE "id" IN (1,2) RETURNING *

它会运作得很好。这里的任何人都可以提供任何解决方法/见解吗?

0 个答案:

没有答案