2016-12-18 3 views
0

워터 라인 ORM을 사용하여 데이터베이스와 인터페이스합니다.인스턴스 메소드에서 워터 라인 모델 업데이트

내가 업데이트 할 필요가 특정 모델에 대한 쿼리
var Waterline = require('waterline'); 

var User = Waterline.Collection.extend({ 
    ...some fields... 
    attributes:{ 
     col_a:{ 
      type:'integer' 
     }, 
     touch_user:function(){ 
      // increment col_a and update in table 
     } 
    } 
}); 

export = module.exports = User; 

가 다음 약속으로 조작 :

나는 새로운 개체로 Waterline.Collections를 확장하고 모듈에 할당입니다.

database.models.users.findAll().where({'id':1}).then(...model manipulation...) 

모델에 액세스 할 때마다 자주 수행하는 작업이 있습니다. 나는이 함수를 인스턴스와 연관된 함수로 캡슐화하여 "touch_user"라는 간단한 호출을 호출 할 수 있고 관련 필드가 호출되는 모델에 대해 업데이트 될 것입니다. 모델은과 같이 조회 후

나는 모델 인스턴스 (예 : .update를() 등) 워터 쿼리 방법에 액세스 할 수 없습니다입니다 :

database.models.users.findAll().where({'id':1).then((user)=>{ 
    user.touch_user(); 
    //user.update // does not work 
}); 

을하지만 그것을 쿼리 때까지 아니라고 레코드와 관련된 데이터를 검색합니다. 내가 user.touch_user을 부탁 () 비슷한 위의 다음과 같은

database.models.users.findAll().where({'id':1).then((user)=>{ 
    user.touch_user(); 
    database.models.users.update(user.id, {'col_a':user.col_a+1}); 
}); 

문제에 사용자 테이블에 col_a를 증가하면 사용자 개체가 정확하게 테이블에 업데이트를 반영하지 않는다는 것입니다.

답변

0

내가 끝내게 된 것은 모델과 인스턴스를 업데이트하는 클래스 메서드를 만드는 것이 었습니다. 내가 원하지만 그렇게

database.models.users.findAll().where({'id':1).then((user)=>{ 
    ...modify user... 
    database.models.users.touch_user(user); 

    ...other changes to user that have to occur here... 
    database.models.users.touch_user(user); 
}); 
처럼
var User = Waterline.Collection.extend({ 
    ...some fields... 
    attributes:{ 
     col_a:{ 
       type:'integer' 
     }, 
    }, 
    // touch_user is a class method here 
    touch_user:function(user){ 
     // update model instance 
     user.col_a += 1; 
     // update database table 
     database.models.users.update(user.id, {'col_a':user.col_a).exec(function(){}); 
    } 
}); 

가 호출 동기화 모델과 테이블을 유지하기 위해 핀치에 있지 않음을 정확히