I want to fetching data from two table that have one to one relation in database using adonisjs. When i'm try to fetch all data from one of table, that result is null.
This is my relation code in model:
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'
}
...
This is my product's model:
class Product extends Model {
static get table()
{
return 'product'
}
static get primaryKey()
{
return 'product_id'
}
}
module.exports = Product
Then, this is my controller
async index ({response}) {
const allProduct = await Cart.query().with('product').fetch();
return response.json({
status:true,
data: allProduct
})
}
edited
This is my cart schema
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()
})
}
...
And this is my product schema:
class ProductSchema extends Schema {
async up () {
const exists = await this.hasTable('product')
if (!exists) {
this.create('product', (table) => {
table.increments()
table.timestamps()
})
}
...
data product above is null. Whats wrong with this code ?
The relationship from Cart
model to Product
is belongsTo
as per your schema.
The primary key of product
table is id
and reference key on cart
table is id_product
as per your schema.
Configure your relationship on cart
model for product
as follows.
product() {
return this.belongsTo("App/Models/Product", "id_product", "id");
}
Fetch cart with products as follows
const cart = await Cart.query()
.with("product")
.fetch();