不确定如何在 AdonisJs 中使用外键保存到数据库

Unsure how to save to database with foreign key in AdonisJs

总结

我正在创建一个摄影应用程序来帮助摄影师跟踪他们的客户。这是我使用 Adonis.JS 的第一个项目,到目前为止我真的很喜欢它,但是在这个问题上停留了一段时间并且无法在任何地方找到答案。我将分享我的模型、控制器和迁移(可能没有正确创建关系,自从我完成任何后端工作以来已经有一段时间了)

工作流程:一个用户有多个客户端,一个客户端有多个服务 需要能够得到用户的服务。

我尝试过的

在我的 ServiceController 中保存时,我尝试过类似的操作:

const user = await auth.getUser();

service.fill({
   name,
   price,
   quantity,
   due_date
});

await user.clients().services().save(service);

return service;

但遗憾的是我收到 500 错误阅读:“user.clients(...).services is not a function”这确实有道理,只是不确定如何解决它。

我工作的一种方式是:

const clients = await Database.table('clients').select('*').where('user_id', user.id);

await Database.table('services')
   .insert({
      name,
      price,
      quantity,
      due_date: dueDate,
      client_id: clients[0].id
   });
    
return service;

我只是觉得那个解决方案不对,考虑到 Adonis 给了 Lucid,感觉有点老套,我不确定;但我觉得该查询有时会引起问题。

型号

用户模型

class User extends Model {
   clients() {
      return this.hasMany('App/Models/Client');
   }
}

客户端模型

class Client extends Model {
   users() {
      return this.belongsToMany('App/Models/User');
   }

   services() {
      return this.hasMany('App/Model/Service');
   }
}

服务模式

class Service extends Model {
   client() {
      return this.belongsTo('App/Models/Client');
   }
}

控制器

服务控制器

  async store ({ auth, request, response }) {
    // Get Authenticated user
    const user = await auth.getUser();

    // Retrieve new service from payload
    const { name, price, quantity, dueDate } = request.all();

    const service = new Service();

    service.fill({
      name,
      price,
      quantity,
      due_date: dueDate
    });

    await user.clients().services().save(service);

    return service;
  }

客户端控制器

    // Get Authenticated user
    const user = await auth.getUser();

    // Retrieve new client from payload
    const { name, email, address, phoneNumber } = request.all();

    const client = new Client();

    client.fill({
      name,
      email,
      address,
      phone_number: phoneNumber
    });

    await user.clients().save(client);

    return client;

迁移

服务模式

class ServiceSchema extends Schema {
  up () {
    this.create('services', (table) => {
      table.increments();
      table.string('name', 255).notNullable();
      table.integer('price', 25).notNullable();
      table.integer('quantity', 25).notNullable().defaultTo(1);
      table.date('due_date', 100).notNullable();
      table.boolean('paid').notNullable().defaultTo(false);

      table.integer('client_id', 25).unsigned().references('id').inTable('clients');
      table.timestamps();
    });
  }

  down () {
    this.drop('services');
  }
}

客户端架构

class ClientSchema extends Schema {
  up () {
    this.create('clients', (table) => {
      table.increments();
      table.string('name', 255).notNullable();
      table.string('email', 255).notNullable();
      table.string('address', 255).notNullable();
      table.string('phone_number', 25).notNullable();

      table.integer('user_id', 25).unsigned().references('id').inTable('users');
      table.timestamps();
    });
  }

  down () {
    this.drop('clients');
  }
}

用户架构

class UserSchema extends Schema {
  up () {
    this.create('users', (table) => {
      table.increments()
      table.string('first_name', 80).notNullable();
      table.string('last_name', 80).notNullable();
      table.string('email', 254).notNullable().unique();
      table.string('password', 60).notNullable();
      table.timestamps();
    });
  }

  down () {
    this.drop('users');
  }
}

预期输出

如果可能的话,我希望我的表格最终看起来像这样:

用户Table

|编号 | first_name | last_name |电邮 |密码 | created_at | updated_at |

客户Table

|编号 |姓名 |电邮 |地址 | phone_number | user_id | created_at | updated_at |

服务Table

|编号 |姓名 |数量 | due_date |付费 | client_id | created_at | updated_at |

并且我需要一种方法来保存对客户端 ID 的引用的服务。我希望用 Lucid 来做这件事,但如果这在这里不适用也没关系。只是想要那种一致性。

我最终决定我应该只通过正文传递 clientId。

服务控制器:

  async store ({ auth, request, response }) {
    // Get Authenticated user
    const user = await auth.getUser();

    // Retrieve new service from payload
    const { name, price, quantity, dueDate, clientId } = request.all();

    const service = await Service.create({
      name,
      price,
      quantity,
      due_date: dueDate,
      client_id: clientId
    });

    return response.status(200).send(service);
  }