Laravel - 参数编号无效:未定义参数

2022-08-30 20:32:00

在Laravel上,为什么我会收到错误

参数编号无效:未定义参数

我已经包含了所有参数。

当我直接在PHPMyAdmin上测试时,它工作正常。

法典:

$results = \DB::select('SELECT client_id,
                               date_format(start_date,"%d/%m/%Y") as start_date,
                               date_format(end_date,"%d/%m/%Y") as end_date,
                               first_name, last_name, phone, postcode
                            FROM hire INNER JOIN client ON client.id = hire.client_id
                            where ((:sdate between start_date and end_date OR :edate between start_date and end_date) OR (:sdate <= start_date and end_date <= :edate)) AND car_id = :car_id', [
        'sdate'  => $start_date,
        'edate'  => $end_date,
        'car_id' => $car_id
    ]
);

变量示例:

$start_date = $inputs['start_date'];  //2015-10-27
$end_date = $inputs['end_date'];     //2015-10-27
$car_id = $inputs['car_id'];         //5

答案 1

查询失败,因为您在查询中重用参数。Laravel使用PDO进行SQL查询。根据文档

不能在预准备语句中多次使用同名的命名参数标记,除非仿真模式处于打开状态。

因此,即使它们具有相同的值,您也必须重命名这些参数。

$results = \DB::select('SELECT client_id,
                           date_format(start_date,"%d/%m/%Y") as start_date,
                           date_format(end_date,"%d/%m/%Y") as end_date,
                           first_name, last_name, phone, postcode
                        FROM hire INNER JOIN client ON client.id = hire.client_id
                        where ((:sdate between start_date and end_date OR :edate between start_date and end_date) OR (:sdate2 <= start_date and end_date <= :edate2)) AND car_id = :car_id', [
    'sdate'  => $start_date,
    'sdate2'  => $start_date,
    'edate'  => $end_date,
    'edate2'  => $end_date,
    'car_id' => $car_id
]
);

答案 2

您正在将所有 SQL 插入到 laravel 的查询生成器方法中。您只需要利用其其他方法:select()

$select = [
    'client_id',
    'start_date',
    'end_date',
    'first_name',
    'last_name',
    'phone',
    'postcode'
];

$results = \DB::table('hire')
        ->join('client', 'client.id', '=', 'hire.client_id')
        ->select($select)
        ->where('car_id', $car_id)
        ->whereBetween('start_date', [$start_date, $end_date])
        ->orWhereBetween('end_date', [$start_date, $end_date])
        ->get();

这些不是您的所有参数,但它应该可以帮助您入门。

如果您不打算使用查询构建器,请尝试执行 :raw($expression)

$results = \DB::raw('SELECT client_id,
                           date_format(start_date,"%d/%m/%Y") as start_date,
                           date_format(end_date,"%d/%m/%Y") as end_date,
                           first_name, last_name, phone, postcode
                        FROM hire INNER JOIN client ON client.id = hire.client_id
                        where ((:sdate between start_date and end_date OR :edate between start_date and end_date) OR (:sdate <= start_date and end_date <= :edate)) AND car_id = :car_id', [
        'sdate'  => $start_date,
        'edate'  => $end_date,
        'car_id' => $car_id
    ]
);

推荐