Create a CRUD from a database view using Gii in Yii2
Asked Answered
S

4

7

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?

Situated answered 24/3, 2016 at 3:59 Comment(0)
A
9

Simple add to your Model class

 public static function primaryKey()
{
    return ['id'];
}
Amylose answered 4/3, 2017 at 13:19 Comment(2)
if there is no primary key in the table then what should one do ?Mcnully
return ['key','value'] ?Amylose
S
3

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.

Swine answered 21/6, 2016 at 8:20 Comment(1)
what if there is no primary key in a table ?Mcnully
B
1

The bug is about mysql, your table should have a PRIMARY KEY in table.

CREATE TABLE Persons (
    P_Id int NOT NULL,
    LastName varchar(255) NOT NULL,
    FirstName varchar(255),
    Address varchar(255),
    City varchar(255),
    PRIMARY KEY (P_Id)    
);

is OK because P_Id is PRIMARY KEY,

on the converse,

CREATE TABLE Persons (
    PersonID int,
    LastName varchar(255),
    FirstName varchar(255),
    Address varchar(255),
    City varchar(255) 
);

is not OK.

The key to solve this problem is let your table have at least one PRIMARY KEY attribute.

Benadryl answered 29/7, 2018 at 12:56 Comment(0)
R
-3

The simplest workarround that comes to my mind would be to, create table that has the same structure as the one your desire (with primary key field). Use that table to create your CRUD. Now just simply replace your newly created table with View.

Rhea answered 24/3, 2016 at 4:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.