yii2获取名称而不是id
问题描述:
我有这个奇怪的问题.我有一个表关系.而且我想查看相关的表字段名称而不是ID.
hi i have this weird problem. i had a table relation. and i want to view the related table field name instead of id.
这是我的模特:
public function getQCat()
{
return $this->hasOne(QbCategory::className(), ['id' => 'q_cat']);
}
这是我的观点:
<?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',
],
]) ?>
视图中的"q_cat"字段我要显示名称而不是ID.我尝试使用"q_cat.name",但提示(未设置).
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).
谢谢.
答
假设您的QbCategory模型是
assuming you QbCategory model is
id
name
,并且您想访问主类中的QbCategory值
您可以通过这种方式访问属性名称
在主要班级
and you want accessing to QbCategory value in your Main Class
you could access to the attribute name in this way
in Main class
添加关系
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
然后您可以为QbCategory名称构建一个吸气剂
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
}
然后在您的主要Clals详细信息视图中
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',
],
]) ?>