我是新手 - Yii2框架中的初学者需要帮助。 我有桌子:
e_rooms:
e_items:
e_units:
e_departments:
在型号Rooms.php中
public function relations()
{
return array(
'items_in_room' => array(self::HAS_MANY, 'Items', 'id_room'),
);
}
public function getItems()
{
return $this->hasMany(Items::className(), ['id_room' => 'id'])
}
在RoomsController.php中:
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
'room_items' => $this->findModel($id)->items,
]);
}
在view.php中:
GridView::widget([
'dataProvider' => new ArrayDataProvider([
'allModels' => $room_items,
'pagination' => [
'pageSize' => 100,
],
'sort' => [
'attributes' => ['number_reference', 'name', 'price'],
],
]),
//'filterModel' => $searchModel,
'columns' => [
['class' => 'yii\grid\SerialColumn'],
[.......]
这显示了这个会议室中的所有项目 - 没关系,但我如何加入表e_units和e_departments来获取名称单位和名称部门而不是ID ID?
答案 0 :(得分:2)
定义与Unit和Department
的关系public function getUnit(){
return $this->hasOne(Unit::className(), ['id' => 'id_unit']);
}
public function getDepartment(){
return $this->hasOne(Department::className(), ['id' => 'id_department']);
}
您可以在gridview中将它们用作以下列:
GridView::widget([
/* ... */
'columns' => [
['class' => 'yii\grid\SerialColumn'],
'id', // item id
'name', // item name
'department.name'
'unit.name'
],
/* ... */
为了避免在视图中出现过多的查询,您可以在构建room_items
数组时加载这些关系
'room_items' => $this->findModel($id)->getItems()->with(['unit', 'department'])->all()
在旁注上,请检查yii2 guidelines for schema design,(旧的yii文档,但同样的指南适用)
你应该很好地理解何时以及为什么要对表,模型和关系使用单/复数命名
答案 1 :(得分:0)
同样的过程不起作用:(
table e_items (id, name, id_room, id_previous_room, id_unit, id_department,....)
table e_rooms (id, name)
table e_units (id, name)
table e_departments (id, name)
在view items / view.php中,我需要这样: 项目:
id => id
name => name
id_room => name_of_room
id_previous_room => name_of_room
id_unit => name_unit
id_department => name_department
我不知道上面是怎么做的...... ItemsController如何在单元,房间等的每个id上进行没有SQL查询的关系