Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a CRUD from a database view using Gii in Yii2

Tags:

php

crud

yii2

gii

I have generated a Model using gii of a mariadb view, which worked.

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).

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';
}

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?

like image 541
Adrian Cornish Avatar asked Mar 24 '16 03:03

Adrian Cornish


2 Answers

Simple add to your Model class

 public static function primaryKey()
{
    return ['id'];
}
like image 183
zakrzu Avatar answered Oct 09 '22 15:10

zakrzu


I had the same issue once. You need to add the function getPrimaryKey to your model class.

public function getPrimaryKey($asArray=false){
    return "id";
}

You can find more details here: http://www.yiiframework.com/doc-2.0/yii-db-baseactiverecord.html#getPrimaryKey()-detail

This should allow you to use the CRUD generator and also take care of the "undefined index: i" error.

like image 21
Richard Schobesberger Avatar answered Oct 09 '22 15:10

Richard Schobesberger