问题
hi i have this weird problem. i had a table relation. and i want to view the related table field name instead of id.
here is my model:
public function getQCat()
{
return $this->hasOne(QbCategory::className(), ['id' => 'q_cat']);
}
here is my view:
<?php echo DetailView::widget([
'model' => $model,
'attributes' => [
'q_cat',
'question:ntext',
'q_c1:ntext',
'q_c2:ntext',
'q_c3:ntext',
'q_c4:ntext',
'q_ans:ntext',
],
]) ?>
that 'q_cat' field in view i want to display name instead of id. i tried using 'q_cat.name' but it says (not set).
thanks.
回答1:
assuming you QbCategory model is
id
name
and you want accessing to QbCategory value in your Main Class
you could access to the attribute name in this way
in Main class
add relation
public function geQcat()
{
return $this->hasOne(QbCategory::className(),
['id' => 'qcat_id']); // qcat_id is the column name in Main class that join QCat to Main
then you can build a getter for for QbCategory name
public function getQcatname() {
return $this->qcat->name; // name is the name of name column in QCat
}
then in your Main Clals Detail View
<?php echo DetailView::widget([
'model' => $model,
'attributes' => [
'qcatname', // this i the ref for getQcatname function in Main Model
'question:ntext',
'q_c1:ntext',
'q_c2:ntext',
'q_c3:ntext',
'q_c4:ntext',
'q_ans:ntext',
],
]) ?>
回答2:
Easier solution
[
'attribute' => 'q_cat',
'value => $model->Qcat->qcat_name
]
来源:https://stackoverflow.com/questions/43927919/yii2-get-name-instead-of-id