我很抱歉我的英语.所以,我有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”中显示来自SUMMARY_FIELD表的相应“scientist_id”.我怎么能这样做?
科学家模型中与表格的关系:
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']);
}
最佳答案 在Model中创建函数:
function getFieldId($model)
{
$string = '';
foreach ($model->summaryFields as $cat) {
$string .= $cat->field_id . " ";
}
return $string;
}
并在视图中访问使用$model-> functionName():
= DetailView::widget([
'model' => $model,
'attributes' => [
[
'attribute'=>'field_id',
'value' => $model->getFieldId($data),
],
],
]); ?>