使用adonisjs中的关系返回数据为空
我想使用adonisjs从数据库中具有一对一关系的两个表中获取数据。当我尝试从表之一中获取所有数据时,该结果为null。
这是我在模型中的关系代码:
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()
})
}
...
上面的数据乘积为空。此代码有什么问题?
回答如下:由于在Cartschema中放置引用时,此数据类型不是字符串,因此输出为null。像这样将数据类型字符串更改为整数
class CartSchema extends Schema {
async up () {
const exists = await this.hasTable('cart')
if (!exists) {
this.create('cart', (table) => {
table.increments()
table.integer('id_product').unsigned().references('product_id').inTable('product')
table.timestamps()
})
}
...
使用adonisjs中的关系返回数据为空
我想使用adonisjs从数据库中具有一对一关系的两个表中获取数据。当我尝试从表之一中获取所有数据时,该结果为null。
这是我在模型中的关系代码:
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()
})
}
...
上面的数据乘积为空。此代码有什么问题?
回答如下:由于在Cartschema中放置引用时,此数据类型不是字符串,因此输出为null。像这样将数据类型字符串更改为整数
class CartSchema extends Schema {
async up () {
const exists = await this.hasTable('cart')
if (!exists) {
this.create('cart', (table) => {
table.increments()
table.integer('id_product').unsigned().references('product_id').inTable('product')
table.timestamps()
})
}
...