【问题标题】:Add a computed field in a select using Eloquent使用 Eloquent 在选择中添加计算字段
【发布时间】:2016-04-04 15:05:24
【问题描述】:

我想使用 Eloquent 在我的选择结果中添加一个计算字段。

$dbEntry->query->select('id', '(s1 + s2) as scoreSum')->toSql();
// "select `id`, `(s1` as `s2)` from `mytable`"

我希望:

// "select `id`, `s1` + `s2` as scoreSum from `mytable`"

上下文:在我的现实世界中,我计算的是一个半正弦公式(在一组有限的条目上)。

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    您需要改用原始查询,例如像这样:

    ->select(DB::raw('id, (s1 + s2) as scoreSum'))
    

    确保您也导入了DB

    【讨论】:

    • 我们确定需要原始查询吗?
    • 基本上任何需要操作的东西都需要使用原始查询。由于您有一个(添加),因此应该需要一个原始查询。我有 95% 的把握。 :)
    • @AsTeR 您可以将原始查询限制为仅计算字段:->select('id', DB::raw('(s1 + s2) as scoreSum')),但您仍然需要原始查询来执行您想做的事情。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-12
    • 2015-01-14
    • 2018-04-27
    • 1970-01-01
    • 2013-11-19
    • 2019-03-04
    • 2019-11-19
    相关资源
    最近更新 更多