用于IN子句的Laravel原始查询参数

时间:2017-08-17 12:58:16

标签: php mysql laravel

我使用Laravel DB::select()进行原始查询,在将参数传递给IN子句时遇到问题。

第一次查询:

$team = DB::table('TeamUserLinks')
             ->orderBy('User_Name', 'asc')
             ->lists('User_Name');

第二次查询:

$user_tasks = DB::select("SELECT usr_first_name,usr_last_name,username,
    (SELECT COUNT(*) FROM task_assignee_user t WHERE t.user_id = u.id AND t.task_status = 1) as status_open,
    (SELECT COUNT(*) FROM task_assignee_user t WHERE t.user_id = u.id AND t.task_status = 1 AND t.task_due_date < CURRENT_DATE) as overdue, 
    FROM user u where usr_initials in(" . $team . ")");

也尝试过:

"FROM user u where usr_initials in(?)",array($team));

$team = implode($team) //Not working while passing after implode

usr_initials in('" . $team . "')");//Not working with quotes 

第二个查询总是返回空结果。

1 个答案:

答案 0 :(得分:5)

使用带有字符串的in ()进行正确查询:

WHERE field IN ('String1', 'String2', 'String3')

因此,您需要添加引号逗号

以简单的方式:

 "... FROM user u where usr_initials in('" . implode("', ' ", $team . "')");

但是,当您将'视为名称的一部分时 - 您的查询将被破坏,因此最好使用预准备语句。这样的事情应该有效:

// here we create array of `?` of a size of team.
$marks = array_fill(0, sizeof($team), '?');
// imploding it later will give us a string `?, ?, ?`
// later every `?` will be replaced with a value of `$team`

$user_tasks = DB::select(
    "SELECT usr_first_name,usr_last_name,username,
        (SELECT COUNT(*) FROM task_assignee_user t WHERE t.user_id = u.id AND t.task_status = 1) as status_open,
        (SELECT COUNT(*) FROM task_assignee_user t WHERE t.user_id = u.id AND t.task_status = 1 AND t.task_due_date < CURRENT_DATE) as overdue, 
        FROM user u where usr_initials in(" . implode(',', $marks) . ")", 
    $team
);