【问题标题】:Yii2, how to use another model for display in view fileYii2,如何使用另一个模型在视图文件中显示
【发布时间】:2016-02-12 11:18:10
【问题描述】:

对不起我的英语。所以,我有 3 个具有多对多关系的表。

以及在视图文件中显示属性的这段代码:

    <?= DetailView::widget([
    'model' => $model,
    'attributes' => [
        'scientist_id',
        'scientist_name',
        'scientist_surname',
        'scientist_patronymic',
        'scientist_birthdate',
        'scientist_email:email',
        'scientist_phone',
        'scientist_photo',
        'scientist_status',
        'scientist_job:ntext',
        'scientist_additional_information:ntext',
        'field_id', //display field but no data
    ],
]) ?>

所以我需要在“field_id's”中显示SUMMARY_FIELD表中对应的“scientist_id”。我该怎么做?

与 Scientist 模型中的表的关系:

    public function getSummaryFields()
{
    return $this->hasMany(SummaryField::className(), ['scientist_id' => 'scientist_id']);
}
public function getFields()
{
    return $this->hasMany(Field::className(), ['field_id' => 'field_id'])->viaTable('summary_field', ['scientist_id' => 'scientist_id']);
}

SummaryField 模型中的关系:

    public function getField()
{
    return $this->hasOne(Field::className(), ['field_id' => 'field_id']);
}

/**
 * @return \yii\db\ActiveQuery
 */
public function getScientist()
{
    return $this->hasOne(Scientist::className(), ['scientist_id' => 'scientist_id']);
}

【问题讨论】:

  • 如果使用 gii 创建 CRUD,则在模型中显示生成的关系,否则在模型中创建关系。
  • 显示您的相关模型..我们可以检查您是否已经拥有正确的关系。
  • @InsaneSkull 已更新.. 你的意思是?
  • 使用关系访问其他字段的简单方法是relationName.field_name
  • @InsaneSkull 以及如何从 field_id 获取数组?

标签: php yii2


【解决方案1】:

在模型中创建函数:

function getFieldId($model)
{
   $string = '';
   foreach ($model->summaryFields as $cat) {
      $string .= $cat->field_id . " ";
   }
return $string;
}

并在视图中使用$model-&gt;functionName()

<?= DetailView::widget([
   'model' => $model,
   'attributes' => [ 
     [
     'attribute'=>'field_id',
     'value' => $model->getFieldId($data),
     ],
   ],
]); ?>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-21
    • 1970-01-01
    • 1970-01-01
    • 2021-09-01
    • 2015-04-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多