You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel 8中如何实现Delay列的求和统计?

在Laravel 8中查询PLC数据库tbl_StatusLog表的Delay列求和值

方法一:使用DB门面直接查询

如果不需要Eloquent模型,直接通过DB门面指定PLC数据库连接,添加筛选条件后调用sum()方法即可:

// 替换连接名、条件为实际业务需求
$totalDelay = DB::connection('plc')
    ->table('tbl_StatusLog')
    ->where('your_condition_column', 'your_condition_value') // 单条件示例
    // 可追加更多条件,比如范围查询:->whereBetween('log_time', [$start, $end])
    ->sum('Delay');

说明:connection('plc')中的plc是你在config/database.php中配置的PLC数据库连接名称,需确保该连接配置正确。

方法二:使用Eloquent模型查询

如果需要复用该表的查询逻辑,可先创建对应模型:

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class StatusLog extends Model
{
    protected $connection = 'plc'; // 指定PLC数据库连接
    protected $table = 'tbl_StatusLog'; // 绑定目标表
    public $timestamps = false; // 若表无默认时间戳字段需关闭
}

之后在控制器或业务代码中调用模型查询求和:

use App\Models\StatusLog;

$totalDelay = StatusLog::where('your_condition_column', 'your_condition_value')
    ->sum('Delay');

关键配置说明

确保config/database.php中已正确配置PLC数据库连接,示例如下(根据数据库类型调整驱动,如sqlsrv、mysql等):

'connections' => [
    // 其他数据库连接...
    'plc' => [
        'driver' => 'mysql',
        'host' => env('PLC_DB_HOST', '192.168.1.100'),
        'port' => env('PLC_DB_PORT', '3306'),
        'database' => env('PLC_DB_DATABASE', 'plc_system'),
        'username' => env('PLC_DB_USERNAME', 'plc_user'),
        'password' => env('PLC_DB_PASSWORD', 'plc_pass'),
        'charset' => 'utf8',
        'collation' => 'utf8_unicode_ci',
    ],
],

内容的提问来源于stack exchange,提问作者Aboolfazl Ehsani

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 11:10:40