Laravel 5自定义查询无效的参数编号

时间:2017-07-10 22:58:31

标签: php laravel laravel-5

在Laravel 5中,我正在尝试进行客户查询。我的代码是这样的:

$ params = array(             'criteria'=> $标准,             'criteria1'=> $标准         );

    //Define the SQL
    $sql = 'SELECT * FROM ' . $this -> _taskTableName .' 
    JOIN ' . $this -> _userTableName .' ON 
    ' . $this -> _userTableName .'.id = ' . $this -> _taskTableName .' .client_id 
    WHERE notes LIKE \'%:criteria%\' OR name LIKE \'%:criteria1%\' ';


    //Exeute the search
    $tasks = DB::statement(DB::raw($sql),$params);

除非我不断收到此错误,即使我删除了DB :: raw,我也尝试过DB :: select。

SQLSTATE[HY093]: Invalid parameter number: :criteria (SQL: SELECT * FROM tasks 
JOIN users ON 
users.id = tasks .client_id 
WHERE notes LIKE '%:criteria%' OR name LIKE '%:criteria1 %' )
in Connection.php (line 647)
at Connection->runQueryCallback(object(Expression), array('criteria' => 'Devin', 'criteria1' => 'Devin'), object(Closure))
in Connection.php (line 607)
at Connection->run(object(Expression), array('criteria' => 'Devin', 'criteria1' => 'Devin'), object(Closure))
in Connection.php (line 450)

有没有人知道为什么会发生这种情况以及如何解决?

2 个答案:

答案 0 :(得分:0)

尝试将DB:select()$params数组一起用作第二个参数,如下所示:

$params = array( 'criteria' => $criteria, 'criteria1' => $criteria );

//Define the SQL
$sql = 'SELECT * FROM ' . $this -> _taskTableName .' 
JOIN ' . $this -> _userTableName .' ON 
' . $this -> _userTableName .'.id = ' . $this -> _taskTableName .' .client_id 
WHERE notes LIKE \'%:criteria%\' OR name LIKE \'%:criteria1%\' ';


//Exeute the search
$tasks = DB::select($sql, $params);

答案 1 :(得分:0)

你可以这样做

$sql = 'SELECT * FROM ' . $this -> _taskTableName .' 
        JOIN ' . $this -> _userTableName .' ON 
        ' . $this -> _userTableName .'.id = ' . $this -> _taskTableName .' .client_id 
        WHERE notes LIKE \'%?%\' OR name LIKE \'%?%\' ';
    DB::select($sql,array($criteria,$criteria));