I am using the following functions in my Contact model
public static function getParents()
{
return $this->hasMany(Contact::className(), ['parent_id' => 'id']);
}
I want to get the return of this array in the filter attribute of my view:
[
'attribute' => 'parent_id',
'value' => function ($model) {
return $model->parent ? $model->parent->name : null;
},
'hAlign' => 'left',
'vAlign' => 'middle',
//'filter' => ArrayHelper::map(Contact::find()->where(['<>', 'parent_id', 0])->orderBy('name')->asArray()->all(), 'id', 'name'),
'filter' => ArrayHelper::map(Contact::parents()->asArray()->all(), 'id', 'name'),
'filterWidgetOptions' => [
'pluginOptions' => ['allowClear' => true],
],
'filterInputOptions' => ['placeholder' => 'Parent'],
'format' => 'raw'
],
but I get the following error: Call to undefined method common\models\Contact::parents()
the rest of the relations work fine for example the attribute $model->parent
I was using the following code but it is wrong because dosn't brings the name of the parent_id within the same table but the name of the records with parent_id
'filter' => ArrayHelper::map(Contact::find()->where(['<>', 'parent_id', 0])->orderBy('name')->asArray()->all(), 'id', 'name'),
I managed to fix my filter using 2 queries in the form but is not very elegant:
$subQuery = Contact::find()->select('parent_id')->where(['<>', 'parent_id', 0]);
$parents = ArrayHelper::map(Contact::find()->where(['in', 'id', $subQuery])->orderBy('name')->asArray()->all(), 'id', 'name')
UPDATED AFTER CORRECT ANSWER
I put the logic in the module to reuse it in other places and used getParentsArray instead of just parentsArray
public static function getParentsArray() {
$subQuery = Contact::find()->select('parent_id')->where(['<>', 'parent_id', 0]);
$parents = ArrayHelper::map(Contact::find()->where(['in', 'id', $subQuery])->orderBy('name')->asArray()->all(), 'id', 'name');
return $parents;
}
in views or controllers
$parents = Contact::getParentsArray();