I need to be able to convert a hasMany()
relation, which queries and return an array
into a hasOne()
relation which returns object|null
.
Use case:
public function getItems() : \yii\db\ActiveQuery {
return $this->hasMany(Item::class, ['parent_id' => 'id']);
}
I want to create a relation which returns one specific Item
object (or null
if it does not exist).
I would like to do something like this:
public function getPrimaryItem() : \yii\db\ActiveQuery {
return $this->getItems()->andWhere(["primary"=>true])->toHasOne();
}
Please do not tell me to call ->one()
on the original query, because that is not going to solve the problem. I need to be able to:
- call
$model->primaryItem
and receive eitherItem
ornull
- call
$model->getPrimaryItem()
and receive the relation'sActiveQuery
You can toggle it by
multiple
property of\yii\db\ActiveQuery