yii2获取名称而不是id [英] yii2 get name instead of id

查看:261
本文介绍了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',
        ],
    ]) ?>

这篇关于yii2获取名称而不是id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆