7

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;
cms
  • 101
  • 1
  • 1
  • 7
  • Check the following links. Might be helpful http://stackoverflow.com/questions/25469689/yii2-update-field-with-query-builder/25580836#25580836 – Kshitiz Sep 18 '14 at 05:59

3 Answers3

9

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.

Kunal Dethe
  • 1,254
  • 1
  • 18
  • 38
  • If the above answer has worked fine for you then accept the answer so that it is not listed under the 'Unanswered' list anymore. – Kunal Dethe Sep 19 '14 at 09:49
4

Try this code:

$users=[1,2,3];
User::find()->where('id IN('.$users.')');
Sarvar Nishonboyev
  • 12,262
  • 10
  • 69
  • 70
1
 [
   '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.

cms
  • 101
  • 1
  • 1
  • 7
  • Say you get all 3 records then you need to display them as comma separated or something like that? – Kunal Dethe Sep 18 '14 at 05:58
  • Updated the answer. It will return comma separated titles but if you need to return in some other format then modify accordingly. – Kunal Dethe Sep 18 '14 at 06:02