2017-06-15 63 views
2

我是sailsjs的新手。嘗試將我的應用程序後端更改爲sailsjs。有一個我需要使用的現有數據庫。獲取此空的錯誤嘗試使用一個-to-many關聯:Sailsjs一對多空結果

{ 
    "Result": [ 
    { 
     "newCars": [], 
     "name": 'Someone', 
     "id": 1 
    } 
    ] 
} 

這些是我有兩個示例表的結構:

table user 
id | name 
1 | Someone 


table new_car 
name | user_id 
Audi | 1 
BMW  | 1 

型號: (我不知道namings的 - 協會,收集和VIA)

//UserController.js 
module.exports = { 
    tableName: 'user', 
    attributes: { 
    name: { 
     type: 'string' 
    }, 
    newCars: {    //i can name this anything? 
     collection: 'newCar',  //should this be new_car (table name)? 
     via: 'user'   //this is one-side table name? 
    } 
    }, 
    autoCreatedAt: false, 
    autoUpdatedAt: false 
}; 


//NewCarController.js 
module.exports = { 
    tableName: 'new_car', 
    attributes: { 
     name: { 
      type: 'string' 
     }, 
     users: { 
      model: 'User' 
     }   
    }, 
    autoCreatedAt: false, 
    autoUpdatedAt: false 
}; 

控制器:

Role.find(1).populate('newCars').exec(function (err, result){ 
    res.json({Result: result}); 
}); 

我在評論中添加了一些問題。

回答

1

努力解決它。對於像我這樣的新手來說,這可能是有用的。只需要識別主鍵和外鍵。

//at the one side 
id: { 
    type: 'integer', 
    primaryKey: true 
} 


//at the many side  
user: { 
    columnName: 'user_id', 
    model: 'user' 
} 
1

您需要將collection名稱更改爲newcar。在Sails中,無論何時在via,collection,model中引用模型,您都需要使用小寫字母的名稱。閱讀更多here

注意

你需要允許Sails打造自己的關聯表。例如,您需要創建Models UserCar,並讓Sails爲您做映射。這是通過創建一個User_Car(不一定是相同名稱)的表來完成的,該表將user_id映射到car_id。這可以簡單地通過使用sails-generate-api

$ sails generate api User

$ sails generate api Car

創建兩個apis做現在你的模型是這樣的:

//User.js 
module.exports = { 

    attributes: { 
    name: 'string', 

    cars: { 
     collection: 'car', 
     via: 'user' 
    } 
    } 
}; 

// Car.js 
module.exports = { 

    attributes: { 
    name: 'string', 

    user: { 
     model: 'user' 
    } 
    } 
}; 

現在,您可以通過發送HTTP POST/user創建User和汽車到/car

要創建關聯User=>Car發送HTTP POST/user/:id/car/:id

現在,當您通過GET /user/:id得到User的細節,由user[:id]擁有的所有的Cars將被填充。

+0

謝謝,但仍然沒有運氣後進行更改你建議。看我的表格結構和你的評論,應該'通過'是'用戶'或'user_id'。注意,嘗試將其更改爲user_id,但仍爲空結果:( – aiiwa

+0

是由'Sails'適配器創建的'user_id'字段? –

+0

不,我的數據庫在嘗試sailsjs之前存在。user(id,name)和new_car(name,user_id) – aiiwa