Mysql 使用adonisjs中的关系返回的数据为空
我想使用adonisjs从数据库中具有一对一关系的两个表中获取数据。当我试图从其中一个表中获取所有数据时,结果为空 这是我在模型中的关系代码:Mysql 使用adonisjs中的关系返回的数据为空,mysql,node.js,database-relations,adonis.js,Mysql,Node.js,Database Relations,Adonis.js,我想使用adonisjs从数据库中具有一对一关系的两个表中获取数据。当我试图从其中一个表中获取所有数据时,结果为空 这是我在模型中的关系代码: class Cart extends Model { product () { return this.hasOne('App/Models/Product') } static get table() { return 'cart' } static get prima
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中放置引用,所以输出为空。此数据类型不是字符串。将数据类型字符串更改为如下所示的整数
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()
})
}
...
根据您的模式,从
购物车
模型到产品
的关系属于到
。根据您的架构,
product
表的主键是id
,cart
表上的参考键是id\u product
在购物车
模型上为产品
配置您的关系,如下所示
product() {
return this.belongsTo("App/Models/Product", "id_product", "id");
}
取购物车和产品如下
const cart = await Cart.query()
.with("product")
.fetch();
你能分享产品和购物车表的模式吗?我已经在添加我的模式@RajeevRadhakrishnan了