Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use select where in query in yii2

Tags:

gridview

yii2


It returns no title. So what can I change in the query?

$query = (new Query())->select('title')->from('topics')->where(['id' => [1, 2, 3]]);
return $query->title;
like image 583
cms Avatar asked Sep 18 '14 04:09

cms


3 Answers

Your query is formed something like -

SELECT title FROM topics WHERE id IN (1,2,3);

So you will get array of array. Also you need to execute the query.

Try -

$query = (new \yii\db\Query())->select(['title'])->from('topics')->where(['id' => [1, 2, 3]]);
$command = $query->createCommand();
$data = $command->queryAll();
$titles = '';
foreach($data as $row) {
    $titles .= $row['title'] . ', ';
}
return rtrim($titles, ', ');

You will get the title for each record, comma separated.

like image 199
Kunal Dethe Avatar answered Sep 20 '22 11:09

Kunal Dethe


Try this code:

$users=[1,2,3];
User::find()->where('id IN('.$users.')');
like image 43
nsv Avatar answered Sep 17 '22 11:09

nsv


 [
   'attribute' => 'topic_id',
   'format' => 'raw',
   'value' => function($data){
    $query = (new Query())->select(['title'])->from('topics')->where(['id' => [1, 2, 3]]);
      $command = $query->createCommand();
      $data= $command->queryAll();
      foreach($data as $row)
        return  $data['title'];
      }
 ],

m put this code but here error generate this.

Undefined index: title

title is available for topics table.

like image 45
cms Avatar answered Sep 19 '22 11:09

cms