✨ Basics
Queries

Queries with LucidJS

Find by (or fail)

    return await Product.findByOrFail('id', id)
      .then((product) => {
        product.delete()
      })
      .catch(() => {
        throw new AppError('Unable to delete product')
      })

Select

    return await Product.query().select("id",
      "name",
      "description",
      "price",
      "currency",
      "is_popular",
      "image",
      "is_subscription",
      'subscription_period',
      'before_price',
      "is_active").orderBy("created_at", "desc").exec();

Update from data

  const product = await Product.query().where("id", data.id).firstOrFail();
 
 
    product.merge(data);
    await product.save();

Simple update

    //Getting the user by a findby...
    user.name = payload.name;
    user.surname = payload.surname;
    await user.save();

Where

await Otp.query().where("user_id", user.id).where("otp", otp).first();

Where with pivots

await user.related("products").pivotQuery().where("product_id", product.id).exec();

Query pivot

import db from "@adonisjs/lucid/services/db";
 
await db.from("product_user")
    .where("subscription_id", subscription.id)
    .update("subscription_status", subscription.status)
    .update("subscription_end_date", DateTime.fromSeconds(subscription.current_period_end))
    .update("subscription_start_date", DateTime.fromSeconds(subscription.start_date))
    .first();

Resources

More on: