在Yii2中使用Gii从数据库视图创建CRUD [英] Create a CRUD from a database view using Gii in Yii2
问题描述
我已经使用mariadb视图的gii生成了一个模型,该模型可以正常工作。
I have generated a Model using gii of a mariadb view, which worked.
然后尝试为模型使用gii CRUD生成器,我得到了错误
Then trying use the gii CRUD generator for the model, I get the error
The table associated with app\models\Future must have primary key(s).
这是完全可以理解的,因为视图没有PK。我发现了一些建议,说要向模型中添加primaryKey函数,所以我尝试了
Which is perfectly understandable as the the view does not have a PK. I found some advice that says to add a primaryKey function to the model so I tried
public function primaryKey()
{
return 'id';
}
id为列名,实际上是基础表中的PK,这是视图的一部分。但这会失败,并发生以下异常
With id being the column name which is actually the PK in the underlying table, which is part of the view. But this fails with an exception
Cannot make static method yii\db\ActiveRecord::primaryKey() non static in class app\models\Future
所以我尝试将方法设为静态,但随后抛出新异常
So I tried making the method static but it then throws new exception
Undefined index: i
1. in /home/adrian/projects/mtview/mtview/vendor/yiisoft/yii2-gii/generators/crud/Generator.php at line 509
是否可以解决此问题,或者
Is there a way around this, or is it now impossible to use gii to generate code for Database views?
推荐答案
简单添加到模型类
public static function primaryKey()
{
return ['id'];
}
这篇关于在Yii2中使用Gii从数据库视图创建CRUD的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!