2016-09-24 78 views
0

我想通過連接一個名爲account_id的列來使用bookshelf返回相關的行。我之前已經將這一切都工作正常,當它被'id'列鏈接時,但是由於某種原因,我們不得不將它改變爲不同的東西。Bookshelf withRelated ignored foreignkey

我的書架代碼看起來是這樣的:

var Accounts = bookshelf.Model.extend({ 
    tableName: 'accounts', 
    hasTimestamps: true, 
    dailyTasks: function() { 
    return this.hasMany(dailyTasks, 'account_id'); 
    }  
}); 

var dailyTasks = bookshelf.Model.extend({ 
    tableName: 'accounts_daily_tasks', 
    hasTimestamps: true, 
    account: function() { 
    return this.belongsTo(Accounts, 'account_id') 
    } 
}); 

該表的模式看起來像這樣:

|---------|----------------------------| 
| id | account_id (primary key) | 
|---------|----------------------------| 
| 12 |  34     | 
|---------|----------------------------| 

accounts_daily_tasks

| id (primary key) | account_id | 
|-----------------------|---------------| 
| 12     |  34  | 
|-----------------------|---------------| 

哪些索引賬表列ACCOUNT_ID

當我運行以下命令:

Accounts.where('user_id', user_id).fetchAll({ 
          withRelated: ['dailyTasks'] 
         }) 

我得到dailyTasks返回空。但是,在數據庫中,它們都被連接起來了。

當我調試我看到它的調用此:

select `accounts_daily_tasks`.* from `accounts_daily_tasks` where `accounts_daily_tasks`.`account_id` in (1, 3, 4)' } 

因此,事實上,它的搜索in (1,3,4)告訴我它是由列名爲id,而不是ACCOUNT_ID搜索。我覺得我已經嘗試了一切,但只是無法得到這個工作。

+0

2表格的模式是什麼? – dmlittle

+0

我編輯了帖子並添加了基本的表架構 –

回答

0

所以我設法弄明白了,我在賬戶模型中缺少'idAttribute'。所以我把它改爲:

var Accounts = bookshelf.Model.extend({ 
    tableName: 'accounts', 
    hasTimestamps: true, 
    idAttribute: 'account_id', 
    dailyTasks: function() { 
    return this.hasMany(dailyTasks, 'account_id'); 
    } 
}); 

嘿presto,它所有的工作。