2016-08-07 54 views
0

我試圖在書架的任何想法中獲得以下查詢? (這個查詢工作,並返回所需的結果)書架的嵌套查詢

SELECT "restaurants".*, "meals".*, (select count(*) from "public"."visitors" as "visitors" where "visitors"."meal_id" = "meals"."id") as "visitorsMealsCount" FROM "public"."restaurants" as "restaurants" inner join "public"."meals" as "meals" ON "meals"."restaurant_id" = "restaurants"."id" WHERE "restaurants"."id" = '123' 

還有一個問題,我使用的是屬於關聯和的hasMany(例如)後,我預計返回的對象將是類似於

restaurants (obj) 
    meals (obj) 
    visitorsMealsCount (attribute) 

回答

0

對我而言,您的SQL語句與Bookshelf等ORM工具的概念不匹配,它既不會返回餐館也不會返回膳食,而是一個巨大的混合物。

至於你的第二個問題:如何使用new Restaurant({id: '123'}).fetch({ withRelated: ['meals']})

visitorsMealsCount:在documentation I see

adminAccounts: function() { 
    return this.belongsToMany(Account).query({where: {access: 'admin'}}); 
}, 

所以也許

visitorsMealsCount: function() { 
    return this.belongsToMany(Visitor).count(); 
} 

的作品? (我還沒試過。)