Chinmay235
Chinmay235

Reputation: 3414

YII 1.1 - Query Builder: How to fetch multiple IN operator record in the FETCH_KEY_PAIR format

We are facing some problem for fetch record in PDO format. See below my example code:

$getCategories= Yii::app()->db->createCommand()
        ->select('id,category_name')
        ->from('content_categories')
        ->where('id IN (:id)', array(':id'=>$getContentList['content_category_value']))
        //->where("id IN ({$getContentList['content_category_value']})")
        ->queryAll();
print_r($getCategories); exit;

Output:

Array
(
    [0] => Array
        (
            [id] => 1525
            [category_name] => TV 
        )

)

Above query $getContentList['content_category_value']) returns 1525,45 but we are getting only single record.

When we manually execute query:

SELECT * FROM `content_categories` WHERE `id` IN (1525,45);

It returns:

enter image description here

Actually we have two category but above query fetch only one. Could you please check and help me to how we show multiple record fetch by using PDO concept.

Upvotes: 1

Views: 210

Answers (3)

Chinmay235
Chinmay235

Reputation: 3414

I have solved this one. Here is the solution.

Code:

$getCategories= Yii::app()->db->createCommand()
    ->select('id,category_name')
    ->from('content_categories')
    ->where(array('in', 'id', array($getContentList['content_category_value'])))
    ->queryAll();
print_r($getCategories); exit;

Upvotes: 0

rob006
rob006

Reputation: 22174

If $getContentList['content_category_value'] is a string, then it will be used in query as a string. So you're probably getting something like this:

SELECT * FROM `content_categories` WHERE `id` IN ('1525,45');

If you want to build IN condition, you need to use array of values with IN operator:

->where(['in', 'id', explode(',' $getContentList['content_category_value'])])

Upvotes: 1

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38502

Not tested but you can make a try like this,

 $getCategories= Yii::app()->db-
 >createCommand()
    ->select('id,category_name')
    ->from('content_categories')
    ->where(array('in', 'id', 
    $getContentList['content_category_value']))    
    ->queryAll();
print_r($getCategories); exit;

Upvotes: 0

Related Questions