hpaknia
hpaknia

Reputation: 3118

how to get all related model IDs in Yii?

Suppose $model hase some items (one to many relationship), So in Yii $model->items returns an array of item models.
How can I get an array of IDs of related items. This means each element of returned array is an integer.

Upvotes: 1

Views: 4609

Answers (3)

Nagibaba
Nagibaba

Reputation: 5418

Another variant.

Yii::app()->db->createCommand("SELECT id FROM items WHERE model_id=".$model->id)->queryColumn()

This will get all IDs from table as array

Upvotes: 0

Andriy Leshchuk
Andriy Leshchuk

Reputation: 476

Here is an example of direct query, run from Model:

$this->getDbConnection()->createCommand("SELECT id FROM items WHERE model_id = :modelId")->bindParam(":modelId", $model->id, PDO::PARAM_STR)->queryColumn();

In result you will get numeric Array() with IDs from the table as values.

Upvotes: 2

soju
soju

Reputation: 25322

You should simply write your own function for this, e.g.

public function getItemsIDs()
{
  $ids = array();
  foreach($this->items as $item)
    $ids[] = $item->id;
  return $ids;
}

After you just have to call $model->itemsIDs.

EDIT : as darkheir said in its comment, you should consider using DAO.

Upvotes: 3

Related Questions