gpt4 book ai didi

php - 如何在 Laravel Eloquent 计算列上执行 WHERE 子句?

转载 作者:行者123 更新时间:2023-11-29 03:22:18 25 4
gpt4 key购买 nike

我正在尝试根据表中的其他列计算 Laravel 中的列,但我无法对它们执行 WHERE,因为 MySQL 不允许这样做。

我认为我需要一个子查询。我可以像这样在 MySQL 中做到这一点:

SELECT * FROM(
SELECT
@inactive_percentage:=((UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(APP_UPDATE_DATE))) / (UNIX_TIMESTAMP(DEL_TASK_DUE_DATE) - UNIX_TIMESTAMP(APP_UPDATE_DATE)) * 100 AS inactive_percentage,
IF(@inactive_percentage <= 33, "low", IF(@inactive_percentage >= 33 && @inactive_percentage <= 66, "normal", "high")) AS inactive

FROM APP_CACHE_VIEW
) as foo WHERE `inactive`='low'

但我不知道如何在 Laravel 中做同样的事情。我在网上有一些引用资料,但它们对我来说毫无意义。我如何将其翻译成 Eloquent 代码?

最佳答案

将 DB::raw 用于您的自定义子查询。

$datas = DB::table( DB::raw('SELECT
@inactive_percentage:=((UNIX_TIMESTAMP(NOW()) - UNIX_TIMESTAMP(APP_UPDATE_DATE))) / (UNIX_TIMESTAMP(DEL_TASK_DUE_DATE) - UNIX_TIMESTAMP(APP_UPDATE_DATE)) * 100 AS inactive_percentage,
IF(@inactive_percentage <= 33, "low", IF(@inactive_percentage >= 33 && @inactive_percentage <= 66, "normal", "high")) AS inactive
FROM APP_CACHE_VIEW as foo') )->where('active','low')->get();

then
foreach($datas as $data){
//Your data processing / formatting
}

关于php - 如何在 Laravel Eloquent 计算列上执行 WHERE 子句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42220471/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com