【问题标题】:Where do I execute native SQL queries in Loopback 4?在 Loopback 4 中,我在哪里执行本机 SQL 查询?
【发布时间】:2021-05-26 07:35:14
【问题描述】:

我是 Loopback 4 的新手,我一直在尝试执行原生 SQL 查询。我找到了怎么做,问题是没有任何线索将它放在我的代码中以使其工作......这是我找到的documentation

我需要知道我应该把这个放在哪里:

const result = await repository.execute('SELECT * FROM Products');

在我的 Loopback 项目中,它有很多文件。我的目标是制作一个类似 /products/[name] 的 REST 端点,其中 [name] 是动态插入 SQL 查询的参数。

【问题讨论】:

    标签: sql node.js api crud loopback


    【解决方案1】:

    就我个人而言,我会将其实现为新的存储库方法。

    假设您的模型名为 Product,那么您的项目中应该已经存在导出 ProductRepository 类的 src/repositories/product.repository.ts 文件。 (您可以运行lb4 repository 来创建它。)

    export class Product extends DefaultCrudRepository<
      Product,
      typeof Product,
      Product Relations
    > {
      constructor(@inject('datasources.db') dataSource: DbDataSource) {
        super(Product, dataSource);
      }
    
      // your custom method
      async selectByName(name: string): Promise<Product[]> {
        const rawItems = await repository.execute('SELECT * FROM Products');
        // would you like to convert raw data into Product instances?
        return rawItems.map(it => new Product(it));
      }
    }
    

    然后你可以从你的控制器调用这个新的自定义存储库方法,就像你调用的方法一样。 repository.find(filter).

    【讨论】:

    • 非常感谢!你帮了我很多:)
    • @NicoHorn 很乐意为您提供帮助 :) 如果您觉得我的回答有用,请给我投票吗?
    【解决方案2】:

    您可以按照环回文档https://loopback.io/doc/en/lb4/Controller.html 在控制器类中执行此操作。由于您将在控制器本身中定义 REST 端点,您也可以使用 repository.execute() 进行插入,例如

      @get('/products/{name}')
      async doSomething(    
        @param.path.string('name') name: string,
      ): Promise<Product> {
      
      const sql = `SELECT * FROM some_table WHERE some_field="${name}"`;
      await this.productRepository.execute(sql)
            
             --- other lines of code & return value --
      }
    

    【讨论】:

      猜你喜欢
      • 2018-11-30
      • 1970-01-01
      • 2017-03-23
      • 1970-01-01
      • 1970-01-01
      • 2017-09-06
      • 1970-01-01
      • 2015-08-22
      • 1970-01-01
      相关资源
      最近更新 更多