Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/elixir/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Elixir 从SQL查询填充虚拟字段_Elixir_Phoenix Framework_Ecto - Fatal编程技术网

Elixir 从SQL查询填充虚拟字段

Elixir 从SQL查询填充虚拟字段,elixir,phoenix-framework,ecto,Elixir,Phoenix Framework,Ecto,我必须处理一个无法更改的数据库设置,并且必须使用一个特定的SQL查询来计算表中没有字段的值。我怎样才能在外太空工作?以下是我的方法和遇到的问题: 设置 之后,我创建了两个产品 x 我将虚拟x字段添加到产品: lib/testapp/shops/product.ex defmodule Testapp.Shops.Product do 使用exto.Schema 导入外部变更集 模式产品是什么 字段:名称,:字符串 字段:价格,:浮动 字段:x,:整型,虚拟:真castattrs,[:名称,:价格

我必须处理一个无法更改的数据库设置,并且必须使用一个特定的SQL查询来计算表中没有字段的值。我怎样才能在外太空工作?以下是我的方法和遇到的问题:

设置 之后,我创建了两个产品

x 我将虚拟x字段添加到产品:

lib/testapp/shops/product.ex

defmodule Testapp.Shops.Product do 使用exto.Schema 导入外部变更集 模式产品是什么 字段:名称,:字符串 字段:价格,:浮动 字段:x,:整型,虚拟:真castattrs,[:名称,:价格] |>需要验证[:名称,:价格] 终止 终止 我向Testapp.Shops添加了以下函数:

def execute_和_loadsql、参数、模型do 结果=exto.Adapters.SQL.query!Repo,sql,params Enum.mapreult.rows、&Repo.loadmodel、{result.columns、&1} 终止 def列出产品和do sql=从产品中选择*,1作为x;Testapp.Shops.list_产品与_x [调试]查询OK db=1.3ms队列=2.2ms空闲=8177.7ms 从产品中选择*,1作为x;[] [ %Testapp.Shops.Product{ __meta_uu;:exto.Schema.Metadata, id:1, 插入地址:~N[2020-02-1207:29:36], 名称:苹果, 价格:0.5, 更新地址:~N[2020-02-1207:29:36], x:零 }, %Testapp.Shops.Product{ __meta_uu;:exto.Schema.Metadata, id:2, 插入地址:~N[2020-02-1207:29:47], 姓名:Orange, 价格:0.75,, 更新地址:~N[2020-02-1207:29:47], x:零 } ]
我对给定问题的其他解决方案持开放态度。我无法在Elixir程序中计算x的值。我必须使用SQL来计算它,我想使用EXTO。

更好的方法是选择一个结构所需的所有内容,然后将其移动到EXTO.struct。我的做法如下:

def get_products() do
    query = from p in Products,
            select: %{name: p.name, price: p.price, x: fragment("1")}
    query
    |> Repo.all()
    |> Enum.map(fn el -> struct(Products, el) end)
  end

这种方法的优点是我不使用原始字符串查询。你的计算应该放在碎片部分的内部

在我看来,最好让SQL使用片段

Repo.all from p in Product,选择:%{p | x:1} 如果无法实现此功能,Repo.load/2可以使用映射而不是模式

资料= :装载 |>产品架构__ |>Enum.into%{x::integer} |>Repo.load{列,行} 结构产品、数据 如果您想简化这一点,您可以覆盖产品。_架构_;:加载并使用现有的&Repo.loadmodel,{result.columns,&1}:

模式产品是什么 ... 终止 警告:这可能会产生意外影响 你最好不要在外太空的内部活动 除雾模式:1 def uu模式uu:load,do:[{:x,:integer}| super:load] 定义模式参数,do:superarg 我不能使用select:%{name:p.name,price:p.price,x:fragment1}。这是一个更复杂的SQL调用。
def get_products() do
    query = from p in Products,
            select: %{name: p.name, price: p.price, x: fragment("1")}
    query
    |> Repo.all()
    |> Enum.map(fn el -> struct(Products, el) end)
  end