声明。在Adonisjs中使用builder来选择特定的列不起作用
我想从Adonisjs中的表关系中获取数据。我使用.with
函数从表关系中获取数据,但仅用于某些列,但这不起作用。
我的控制器代码如下:
const cart = await Shop.query()
.with('products',(builder)=>{
builder.select('id','product_name')
})
.select('id_shop')
.fetch()
return response.json({
status:true,
message: false,
data: cart
})
但是上面的代码结果仅为id_shop
,如下所示:
[
{
'id_shop': '1'
'products': []
},
{
'id_shop': '2'
'products': []
}
]
编辑
我在这里添加了商店的型号:
class Shop extends Model {
static get table()
{
return 'shop'
}
static get primaryKey()
{
return 'id_shop'
}
products ()
{
return this.hasMany('App/Models/Product','id_shop', 'shop_id')
}
}
以及我产品的型号:
class Product extends Model {
static get table()
{
return 'product'
}
static get primaryKey()
{
return 'id_product'
}
}
我的代码有什么问题?
回答如下:您在模型中输入错误hasMany关系hasMany这样的关系
products ()
{
return this.hasMany('App/Models/Product','shop_id', 'id_shop')
}
您可以尝试这个
声明。在Adonisjs中使用builder来选择特定的列不起作用
我想从Adonisjs中的表关系中获取数据。我使用.with
函数从表关系中获取数据,但仅用于某些列,但这不起作用。
我的控制器代码如下:
const cart = await Shop.query()
.with('products',(builder)=>{
builder.select('id','product_name')
})
.select('id_shop')
.fetch()
return response.json({
status:true,
message: false,
data: cart
})
但是上面的代码结果仅为id_shop
,如下所示:
[
{
'id_shop': '1'
'products': []
},
{
'id_shop': '2'
'products': []
}
]
编辑
我在这里添加了商店的型号:
class Shop extends Model {
static get table()
{
return 'shop'
}
static get primaryKey()
{
return 'id_shop'
}
products ()
{
return this.hasMany('App/Models/Product','id_shop', 'shop_id')
}
}
以及我产品的型号:
class Product extends Model {
static get table()
{
return 'product'
}
static get primaryKey()
{
return 'id_product'
}
}
我的代码有什么问题?
回答如下:您在模型中输入错误hasMany关系hasMany这样的关系
products ()
{
return this.hasMany('App/Models/Product','shop_id', 'id_shop')
}
您可以尝试这个