【问题标题】:yii2 get name instead of idyii2 获取名称而不是 id
【发布时间】:2017-05-12 01:25:29
【问题描述】:

嗨,我有这个奇怪的问题。我有一个表关系。我想查看相关的表字段名称而不是 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' 但它说(未设置)。

谢谢。

【问题讨论】:

  • 能否添加型号查询?
  • 模型查询是什么意思?我会在上面包含模型:)
  • 从哪里获得 $model 的详细视图。
  • 我在哪里找到的?帮帮我,我是新手。谢谢

标签: php model-view-controller yii2


【解决方案1】:

假设你的 QbCategory 模型是

id
name 

并且您希望访问主类中的 QbCategory 值 您可以通过这种方式访问​​属性名称
在主类中

添加关系

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 名称构建一个吸气剂

public function getQcatname() {  
    return $this->qcat->name; // name is the name of name column in QCat 
}

然后在您的 Main Clals 详细视图中

<?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',
        ],
    ]) ?>

【讨论】:

  • 感谢您的回复。但不幸的是,这是一个错误。顺便说一句,我正在使用入门工具包。
  • 显示错误信息 .. (你对初学者工具包是什么意思???).. 无论如何,答案已更新为正确的类名
  • 先生,我做得对。我的另一个问题是。为什么我需要一个吸气剂的名字。当我从gii生成表关系时,我做了一个表关系
  • 为了简单明了使用 getter .. 所以在模型中我有所有集中的访问功能 .. 这是一种编程模式 .. 你可以使用你喜欢的模式 .. 重要的是始终如一地拥有所需的工具
  • 谢谢您,先生。我想到了。我没有遵循模型中的命名约定。相反 qCat.name 我使用 q_cat.name。这就是我来这里的原因。但根据您给出的答案。我做对了:)。一如既往的编程。最简单的解决方案无法弄清楚,你总是想出先进的方法。并错过了它,直到它成为一个问题。有趣的事情嘿嘿。再次感谢您,先生
【解决方案2】:

更简单的解决方案

[
    'attribute' => 'q_cat',
    'value => $model->Qcat->qcat_name
]

【讨论】:

    猜你喜欢
    • 2021-09-10
    • 2021-01-12
    • 2020-11-12
    • 2018-01-16
    • 2019-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-01
    相关资源
    最近更新 更多