【发布时间】:2020-01-30 11:11:18
【问题描述】:
我想使用 adonisjs 从数据库中具有一对一关系的两个表中获取数据。当我尝试从一个表中获取所有数据时,该结果为空。
这是我在模型中的关系代码:
class Cart extends Model {
product () {
return this.hasOne('App/Models/Product')
}
static get table()
{
return 'cart'
}
static get primaryKey()
{
return 'id_cart'
}
static get foreignKey()
{
return 'id_product'
}
...
这是我的产品型号:
class Product extends Model {
static get table()
{
return 'product'
}
static get primaryKey()
{
return 'product_id'
}
}
module.exports = Product
那么,这是我的控制器
async index ({response}) {
const allProduct = await Cart.query().with('product').fetch();
return response.json({
status:true,
data: allProduct
})
}
已编辑
这是我的购物车架构
class CartSchema extends Schema {
async up () {
const exists = await this.hasTable('cart')
if (!exists) {
this.create('cart', (table) => {
table.increments()
table.string('id_product').unsigned().references('product_id').inTable('product')
table.timestamps()
})
}
...
这是我的产品架构:
class ProductSchema extends Schema {
async up () {
const exists = await this.hasTable('product')
if (!exists) {
this.create('product', (table) => {
table.increments()
table.timestamps()
})
}
...
上面的数据产品为空。这段代码有什么问题?
【问题讨论】:
-
能否请您分享产品和购物车表的架构。
-
我已经添加了我的架构@RajeevRadhakrishnan
标签: mysql node.js database-relations adonis.js