php - yii2 الحصول على اسم بدلا من معرف
model-view-controller (2)
مرحبا لدي هذه المشكلة غريبة. كان لي علاقة الجدول. وأريد عرض اسم الحقل الجدول ذات الصلة بدلا من معرف.
هنا هو نموذجي:
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" في طريقة العرض أريد عرض الاسم بدلا من المعرف. حاولت استخدام 'q_cat.name' لكنه يقول (لم يتم تعيين).
شكر.
بافتراض أن نموذج كبكاتيغوري هو
id
name
وتريد الوصول إلى قيمة كبكاتيغوري في الفئة الرئيسية الخاصة بك يمكنك الوصول إلى اسم السمة بهذه الطريقة
في الطبقة الرئيسية
إضافة علاقة
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
ثم يمكنك بناء جتر للحصول على اسم كبكاتيغوري
public function getQcatname() {
return $this->qcat->name; // name is the name of name column in QCat
}
ثم في كلالس الرئيسية عرض التفاصيل
<?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',
],
]) ?>
حل أسهل
[
'attribute' => 'q_cat',
'value => $model->Qcat->qcat_name
]