2017-02-06 23 views
1

私はCompanyCompanyAdminの2種類があります。モデル会社には多くのCompanyAdminがあります。 bookshelfプラグインbookshelf-cascade-deleteを使用して、親会社が削除されたときにCompanyAdminsを削除しようとしています。私もknexを使用してmysql dbを接続します。ここ

は私のモデルです:Bookshelfカスケード削除

const db = bookshelf(connection); 
db.plugin(cascadeDelete); 

const Company = db.Model.extend({ 
    tableName: 'company', 
    idAttribute: 'id', 
    hasTimestamps: true, 
    company_admins: function() { return this.hasMany(CompanyAdmin); }, // console.log(this); 
}, { 
    dependents: ['company_admins'], 
}); 

const CompanyAdmin = db.Model.extend({ 
    tableName: 'company_admin', 
    idAttribute: 'id', 
    hasTimestamps: true, 
    company: function() { return this.belongsTo(Company) }, 
}); 

I にconsole.log(この)でcompany_admins機能は、私はこのデータを取得する場合:

:ここ

ModelBase { 
    tableName: 'company', 
    idAttribute: 'id', 
    hasTimestamps: true, 
    company_admins: [Function: company_admins] } 

は私のDELETEルートハンドラです

.delete((req, res) => { 
    if (req.user) { 
     Company.forge({ 
      id: req.user.attributes.company_id, 
     }) 
     .destroy() 
     .then(() => { 
      res.status(200) 
      .json({ 
       status: 200, 
       error: false, 
      }); 
      req.logout(); 
     }).catch((err) => { 
      console.log(err); 
      res.status(500) 
      .json({ 
       status: 500, 
       error: err.message, 
      }); 
     }); 
    } else { 
     res.status(401) 
     .json({ 
      status: 401, 
      message: 'User not authenticated', 
     }); 
    } 
}); 

このエラーが発生します:

TypeError: Cannot read property 'hasMany' of undefined

誰も同じ問題がありますか?

答えて

0

私はこれを解決しました。本棚を読み込む際にエラーが発生しました。 私は前にして使っていたコード:

import bookshelf from 'bookshelf'; 
const db = bookshelf(connection); 

そして、このような本棚を見ての正しいインポート:以前のコードが機能しなかった理由を

const db = require('bookshelf')(connection); 

かなりわからないが、修正版の作品をまあ!

関連する問題