Bookshelf withRelated 忽略外键

Bookshelf withRelated ignoring foreignKey

我正在尝试将书架用于 return 相关行,方法是通过名为 account_id 的列连接。我之前在 'id' 列链接时一切正常,但后来出于某种原因我们不得不将其更改为不同的东西。

我的书架代码看起来像这样:

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')
  }
});

tables 架构如下所示:

帐户

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

accounts_daily_tasks

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

哪个索引帐户 table 列 account_id

当我 运行 以下内容时:

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

我将 dailyTasks return 编辑为空。但是在数据库中它都被连接起来了。

当我调试时,我看到它正在调用:

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。我觉得我已经尝试了所有方法,但就是无法正常工作。

所以我设法解决了这个问题,我在帐户模型中丢失了 'idAttribute'。所以我改成了:

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

嘿嘿,很快,一切都恢复正常了。