Search code examples
yii2yii2-model

Yii2: How to generate CRUD from MySQL/MariaDB view automatically with Gii


I can quite easily generate a model from MySQL/MariaDB view with Gii, but when I try to generate CRUD, than I recieve the following error message:

The table associated with frontend\models\MyModel must have primary key(s).

See also the discussion in Yii Framework Forum.


Solution

  • The solution is:

    1. add an ID in the view, e.g. using the CONCAT function,

    2. overwrite the method primaryKey in the generated model.

    Here is the code:

    public static function primaryKey()
    {
        return array('view_id');
    }
    

    It is not a standard solution and should be used carefully. Yii does not officially support using active record with views, because different DBMS have different view specs and they usually don't support DB write (2).