2014-10-23 1 views
10

깊은 중첩 된 연관을 채우는 Sails.js/Waterline에는 아직 기본 방법이 없으므로 블루 버드 약속을 사용하여이를 수행하려고 노력하고 있음을 알고 있지만 문제가 생겼다.Sails.js/Waterline 깊게 중첩 된 연관을 채움

성공적으로 사용자와 모든 게시물 (이미지 컬렉션으로 채워짐)이 검색되었습니다 (console.log에 모든 항목이 올바르게 채워져 있음이 표시됨). 그러나 사용자의 "게시물"속성을 무시하고 이전에 검색된 완전히 채워진 게시물을 할당하려고 시도하면 Post.js의 이미지 속성이 제대로 채워지지 않습니다. 이것은 ORM이 Post.js의 이미지 수집을 수동으로 할당하지 못하게하는 것과 같습니다.

내가 뭘 잘못하고 있니? 중첩 된 일대 다 연관을 채우는 가장 좋은 방법은 무엇입니까? 내가 실행하고있어 모든 코드를 붙여 넣은

우는 ....

// Populate nested association 
nested: function (req, res, next){ 
var username = req.param("id"); 

User 
.findOneByUsername(username) 
.populateAll()  
.then(function (user){ 
    var posts = Post.find({ 
     "user": user.id 
    }) 
    .populate('images') 
    .populate('category') 
    .then(function (posts){ 
     return posts; 
    }); 
    return [user, posts]; 
}) 
.spread(function (user, posts){ 
    user.posts = posts; // This won't work.... It assigns all the fields properly but the images collection attribute 
    res.json(user); 
}).catch(function (err){ 
    if (err) return res.serverError(err); 
}); 
} 

// --- User.js Model --- // 
module.exports = { 
    attributes: { 
    ....., 
    posts: { 
     collection: "post", 
     via: "user" 
    }, 
    ..... 
    } 
} 

// --- Post.js Model --- // 
module.exports = { 
    attributes: { 
     ...., 
     user: { 
     model: "user" 
     }, 
     images: { 
     collection: "postImage", 
     via: "post" 
     }, 
     .... 
    } 
} 

// --- PostImage.js Model --- // 
module.exports = { 

    attributes: { 
    ...., 
    post: { 
     model: "post" 
    } 
    }, 
} 

감사합니다,

SAVIO 루 세나

답변

11

이 질문은 오래된 질문 일 수 있지만 답변이있는 것이 좋으므로 sails.js 사용자는 혜택을 누릴 수 있습니다.

돛이 레코드 (배열 내부)를 반환 할 때 연관에 해당하는 레코드의 키가 실제로 getters/setters이고 설정자가 해당 항목을 허용하지 않는 것으로 보입니다. 필요. Object.getOwnPropertyDescriptor(user, 'posts')을 사용하여 확인할 수 있습니다. 원하는대로 해당 속성을 재정의하려면 수행 할 작업은 .toObject으로 전화하거나 (또는 ​​_.clone을 통해 해당 속성을 복제하거나 수동으로 반복하지만 너무 많은 쓰레기가 생길 수 있습니다. 어떤 경우에는 필요한 속성을 가진 새로운 객체를 얻습니다. 그리고 지금 객체를 수정하는 방법에는 제한이 없습니다.

그래서 코드는 다음과 같이 표시됩니다

User 
.findOneByUsername(username) 
.populateAll()  
.then(function (user){ 
    var posts = Post.find({ 
     "user": user.id 
    }) 
    .populate('images') 
    .populate('category') 
    .then(function (posts){ 
     return posts; 
    }); 
    return [user, posts]; 
}) 
.spread(function (user, posts){ 
    user = user.toObject() // <- HERE IS THE CHANGE! 
    user.posts = posts; // It will work now 
    res.json(user); 
}).catch(function (err){ 
    if (err) return res.serverError(err); 
}); 
} 
0

당신은 사용자의 각 게시물의 ID 객체를 덮어해야 .posts 배열. 자세한 내용은이 대답을 확인하십시오 https://stackoverflow.com/a/26452990/4261327.

+1

야니, 당신은 당신의 대답에 더 팔 수 있을까? 모든 종류의 덮어 쓰기를 시도했지만, 이미지가 다 대다 연관이므로 특정 필드를 덮어 쓰지 못하게합니다. –