如何在CASE WHEN中传递数组

时间:2018-05-30 04:09:57

标签: php mysqli yii2

我想在CASE WHEN语句

中传递一个数组
$friendlist = [];
    foreach ($data as $datas) 
    {
        if ($datas['friend_one'] == $id) 
        {
            $friendlist[] = $datas['friend_two'];
        }
        else
        {
            $friendlist[] = $datas['friend_one'];
        }
    }

$query->select('(CASE WHEN (u1.user_id = u2.user_id) THEN "Added" ELSE (CASE WHEN (u1.user_id = '.$friendlist.') THEN "Paid" ELSE "Received" END) END) as trans_type')

对于单个值是可以的,但是当我传递数组时,它给出了“数组到字符串转换”错误。任何解决方案如何传递数组。

4 个答案:

答案 0 :(得分:3)

您无法将数组与字符串进行比较,反之亦然,首先您应该将数组内爆为字符串,然后在IN中使用:

试试这个:

$query->select(
  '(CASE WHEN (u1.user_id = u2.user_id) THEN "Added"
  ELSE (CASE WHEN (u1.user_id IN ('. implode(",", $friendlist). ')) THEN "Paid"
  ELSE "Received" END) END) as trans_type');

答案 1 :(得分:1)

简单implode()可能会打开 SQL注入 - 您应该在对其进行转义之前转义值:

$friendlist = array_map(function ($data) {
    return Yii::$app->db->quoteValue($data);
}, $friendlist);

$query->select([
    'trans_type' => new \yii\db\Expression(
        'CASE WHEN (u1.user_id = u2.user_id) THEN "Added"
            ELSE (
                CASE WHEN (u1.user_id IN (' . implode(',', $friendlist) . ')) THEN "Paid"
                ELSE "Received" END
            ) END'
    ),
]);

或者您可以使用QueryBuilderInCondition - 这将使用预准备语句和参数来构建IN语句:

$params = [];
$condition = Yii::$app->db->queryBuilder
    ->buildCondition(new InCondition('u1.user_id', 'IN', $friendlist), $params);

$query->select([
    'trans_type' => new \yii\db\Expression(
        'CASE WHEN (u1.user_id = u2.user_id) THEN "Added"
        ELSE (
            CASE WHEN (' . $condition . ') THEN "Paid"
            ELSE "Received" END
        ) END',
        $params
    ),
]);

答案 2 :(得分:0)

首先将$friendlist array内嵌到以逗号分隔的字符串中,然后在IN function中传递它。请试试这个。

$friendlist = [];
    foreach ($data as $datas) 
    {
        if ($datas['friend_one'] == $id) 
        {
            $friendlist[] = $datas['friend_two'];
        }
        else
        {
            $friendlist[] = $datas['friend_one'];
        }
    }
$friendlist = implode(",",$friendlist);//implode array into comma separated string

$query->select('(CASE WHEN (u1.user_id = u2.user_id) 
    THEN "Added" ELSE (CASE WHEN (u1.user_id IN ('.$friendlist.')) 
    THEN "Paid" ELSE "Received" END) END) as trans_type');

答案 3 :(得分:-1)

$friendlist = [];
foreach ($data as $datas) 
{
    if ($datas['friend_one'] == $id) 
    {
        $friendlist[] = $datas['friend_two'];
    }
    else
    {
        $friendlist[] = $datas['friend_one'];
    }
}
foreach($friendlist as $value){

$query->select('(CASE WHEN (u1.user_id = u2.user_id) THEN "Added" ELSE (CASE WHEN (u1.user_id = '.$value.') THEN "Paid" ELSE "Received" END) END) as trans_type')
}