【问题标题】:Laravel eloquent query that reflects updated data based on another table dataLaravel 雄辩的查询,反映基于另一个表数据的更新数据
【发布时间】:2018-02-19 06:29:04
【问题描述】:

我已经对这个主题进行了广泛的搜索,但是基于我对 laravel 和 eloquent 的了解(我是新手),由于我阅读了很多信息,我完全不知道如何去做。

我有两个表:products 和 logrent。

products->[id, name, stock]
logrent->[id, product_id, user_id, action]

当产品售出时,会在 logrent 表上生成一个寄存器,其中包含此操作的值(1 表示出租,2 表示退回租用的产品)

我想构建一个雄辩的查询来反映每个产品上的操作,根据 logrent 表上的租金/回报更新真实库存值(如果可能,在另一个虚拟列中)

我怎样才能做到这一点?

编辑:

这就是我想要的,但是在 Eloquent 中,我能做到吗?怎么样?

select jogos.id, jogos.titulo, (jogos.qt + (select sum(case
fluxos.tipoacao when 2 then 1 when 1 then -1 end) from `fluxos` where
fluxos.jogo_id=jogos.id)) as stock from jogos, fluxos group by id;

【问题讨论】:

  • 如果产品被退回(值为2),您是生成一个新的寄存器还是只更新现有的值为1的寄存器?此外,根据用例,除了dates(如added_atreturned_at)用于可追溯性之外,我建议对产品使用Polymorphic Relations
  • 唯一会像日志一样更新的表是“logrent”(当产品被移动和退回时),产品表的库存字段将在此状态下保持静态。此查询的原因只是为了在屏幕上报告,以控制库存
  • 所以基本上您可能有 5 辆汽车出租(库存 = 5),但要知道实际可用的汽车数量,您需要查询 logrent 表以确定里面有什么和什么出去?
  • 正是这样! !!

标签: php mysql laravel orm eloquent


【解决方案1】:

在学习了一点之后,我能够得到它接近我想要的东西。我已经为这个查询安装了一个 sql 格式,所以我可以将它转换为“原始”格式的 eloquent,但我希望它是纯 eloquent 的。有路径吗?

$data = \DB::table("jogos")
      ->select("jogos.id", "jogos.titulo", "jogos.qt",  
           \DB::raw("(select 
               sum(case fluxos.tipoacao when 2 then 1 when 1 then -1 end) 
                   from `fluxos` where fluxos.jogo_id=jogos.id) as stock")->get()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-28
    • 2018-01-26
    • 2021-07-23
    相关资源
    最近更新 更多