Answer the question
In order to leave comments, you need to log in
How to properly use relationships in Yii2?
When generating the Payments model via Gii, the related tables were displayed only in the rules.
Function
public function getStates()
{
return $this->hasOne(PaymentStates::className(), ['id' => 'state']);
}
added manually. Based on this model, I generated PaymentsSearch, where in the search function I added$query->joinWith([
'states' => function ($q2) {
$q2->select(['name']);
}
. Next, search is called in the controller and renderedreturn $this->render('list', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
[
'attribute' => 'states.name',
'format' => 'raw',
'label' => 'Статус платежа',
'value' => function (Payments $p) {
switch ($p->state) {
case 1 : $class = 'fa fa-question'; break;
case 2 : $class = 'fa fa-times'; break;
case 3 : $class = 'fa fa-check'; break;
}
return Html::tag('div',Html::tag('span','', ['class'=>$class])
. ' ' . $p->states->name);
}
]
Answer the question
In order to leave comments, you need to log in
The getStates link returns null, the link does not mean that you have a state for each Payment. Check this point and make a check, either in code:
$state = ($p->states)?$p->states->name:'не определено';
return Html::tag('div',Html::tag('span','', ['class'=>$class]). ' ' . $state);
public function getStateName()
{
$name = 'хз';
if($this->states)
$name = $this->states->name;
return $name;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question