简体   繁体   English

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

[英]Unsure how to save to database with foreign key in AdonisJs

Summary概括

I'm creating a photography app to help photographers keep track of their clients.我正在创建一个摄影应用程序来帮助摄影师跟踪他们的客户。 This is my first project using Adonis.JS and I really enjoy it so far, but been stuck on this problem for a while and can't find an answer anywhere.这是我使用 Adonis.JS 的第一个项目,到目前为止我真的很喜欢它,但是在这个问题上停留了一段时间,无法在任何地方找到答案。 I'll share my Models, Controllers, and Migrations (possibly not creating the relationships right, been awhile since I've done any back-end work)我将分享我的模型、控制器和迁移(可能没有正确创建关系,自从我完成任何后端工作以来已经有一段时间了)

Workflow: A User has many clients, a client has many services Need to be able to get the services from the user.工作流:一个用户有很多客户端,一个客户端有很多服务需要能够从用户那里获取服务。

What I've Tried我试过的

When saving in my ServiceController I've tried things like:保存在我的 ServiceController 中时,我尝试了以下操作:

const user = await auth.getUser();

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

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

return service;

but sadly I get a 500 error reading: "user.clients(...).services is not a function" which does make sense, just not sure how else to go about it.但遗憾的是,我收到一个 500 错误:“user.clients(...).services is not a function”,这确实是有道理的,只是不知道 go 对此有何看法。

One way I had working was:我工作的一种方式是:

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;

I just didn't feel like that solution was right, it felt kind of hacky given that Adonis gives Lucid, and I'm not sure;我只是不觉得那个解决方案是正确的,考虑到阿多尼斯给了 Lucid,感觉有点 hacky,我不确定; but I feel like that query will cause issues at some point.但我觉得该查询会在某些时候引起问题。

Models楷模

User Model用户 Model

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

Client Model客户 Model

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

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

Service Model服务 Model

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

Controllers控制器

Service Controller服务 Controller

  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;
  }

Client Controller客户端 Controller

    // 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;

Migrations迁移

Service Schema服务模式

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');
  }
}

Client Schema客户端架构

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');
  }
}

User Schema用户模式

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');
  }
}

Expected output预期 output

I want my tables to end up looking like this if possible:如果可能的话,我希望我的表格最终看起来像这样:

Users Table用户表

| | id |编号 | first_name |名字 | last_name |姓氏 | email | email | password |密码 | created_at | created_at | updated_at |更新时间 |

Clients Table客户表

| | id |编号 | name |姓名 | email | email | address |地址 | phone_number |电话号码 | user_id |用户 ID | created_at | created_at | updated_at |更新时间 |

Services Table服务表

| | id |编号 | name |姓名 | quantity |数量 | due_date |到期日期 | paid |付费 | client_id |客户 ID | created_at | created_at | updated_at |更新时间 |

and I need a way to save to services with a reference to the client ID.我需要一种方法来参考客户端 ID 来保存服务。 I was hoping to do this with Lucid, but if that's not applicable here that's fine.我希望用 Lucid 来做这件事,但如果这在这里不适用,那也没关系。 Just wanting that consistency.只是想要那种一致性。

I ended up deciding that I should probably just pass the clientId in through the body.我最终决定我应该只通过正文传递 clientId。

Service Controller:服务 Controller:

  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);
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM