Can't Insert data to multiple table

Hello, i’m still new in adonisjs… i have problem here. I have two table: table carts and table cart_details, and then i want to insert data in both tables, but data only can save in one table

This is my controller’s code:

		const trans = await DB.beginTransaction()

		try {
			const cart = request.collect(['id_cart','status'])
			cart.id_cart = nanoid(25)
			cart.status = 1

			const result = await DB.insert(cart).into('carts')

			await trans.commit();

			const detail = request.only(['id_product','id_shop','price'])
			detail.id_product = params.id_product
			detail.id_cart_detail = nanoid(25)
			detail.id_cart = cart.id_cart

			await DB.insert(detail).into('cart_details')

			return response.status(200).json({
				status:true,
				message: 'New cart added',
				data: result
			})
		}catch (e) {
			trans.rollback()

			return response.status(500).json({
		        status: false,
		        message: e.message,
		        data: null,
		    })
		}

And this is my carts model

class Cart extends Model {

   cartDetails ()
   {
   	return this.hasMany("App/Models/CartDetail", "id_cart", "id_cart")
   }

   static get table()
   {
   	return 'carts'
   }

   static get incrementing () {
       return false
   }

   static get primaryKey()
   {
   	return 'id_cart'
   }

}

And this is my cart_details table

class CartDetail extends Model {

	products () {
	    return this.belongsTo("App/Models/Product", "id_product", "product_id");
	}

	carts () {
	    return this.hasMany('App/Models/Cart','id_cart', 'id_cart')
	}

	static get table()
	{
		return 'cart_details'
	}

	static get incrementing () {
	    return false
	}

	static get primaryKey()
	{
		return 'id_cart_detail'
	}

}

but the result of code above only can inserting in cart_details table, what’s wrong with my code ?

1 Like

This function returns a list [{id_cart: … , status: … } …] from posts where fields are named id_cart[0], id_cart[1] and so on

See here https://adonisjs.com/docs/4.1/request#_request_collection