【发布时间】:2015-03-26 12:14:28
【问题描述】:
我使用 yii2,我有两个带键的表:
第一:
machine
machine_serial PK,name
第二: 操作系统
id PK,os_name, machine_serial PFK
关于关系 1:N
我使用 CRUD 为机器和操作系统生成模型 我想在一个视图中使用 GridView 从两个模型中获取数据,我一直在使用主键数据
我的网格视图:
GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
'os_name',
'machine_serial',
'machine.name',
[
'class' => 'yii\grid\ActionColumn',
'contentOptions' => ['style' => 'width:50px;'],
'header' => 'Actions',
'template' => '{view}',
'buttons' => [
//view button
'view' => function ($url, $dataProvider) {
return Html::a('view',
['view', 'id' => $dataProvider->id,
'machine_serial' => $dataProvider->machine_serial],
['class' => 'btn btn-primary']);
},
]
],
],
]);
但我得到错误:
获取未知属性:backend\models\Node::machine
我是初学者,所以请帮忙:)
型号操作系统:
namespace backend\models;
use Yii;
class Node extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'os';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['id'], 'integer'],
[['machine_serial'], 'string', 'max' => 8]
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'id' => 'ID',
'machine_serial' => 'Machine Serial',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getMachineSerial()
{
return $this->hasOne(Machine::className(), ['machine_serial' => 'machine_serial']);
}
}
模型机:
namespace backend\models;
use Yii;
use yii\db\Query;
class Machine extends \yii\db\ActiveRecord
{
/**
* @inheritdoc
*/
public static function tableName()
{
return 'machine';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['machine_serial'], 'required'],
[['name'], 'string', 'max' => 30]
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'machine_serial' => 'Machine Serial',
'name' => 'Name',
];
}
/**
* @return \yii\db\ActiveQuery
*/
public function getOs()
{
return $this->hasMany(Os::className(), ['machine_serial' => 'machine_serial']);
}
}
在操作系统控制器中:
public function actionIndex()
{
$searchModel = new NodeSearch();
$dataProvider = $searchModel->search(Yii::$app->request->queryParams);
return $this->render('index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
]);
}
【问题讨论】:
-
您能出示您的型号代码吗?
-
并显示
$dataProvider代码。 -
好的,我更新我的查询