databaseyii2crudgii

How to generate gii crud Yii2 without Primary Key?


How can i generate the crud wihtout primary key because, my dabatase, this table don't have a primary key. there is FK only. when i try to generate it will be like this image.

Thank you for your help.


Solution

  • I think, it is not very good to use CRUD without PK. But, if there are no other options, you can add fake PK variable to table temporarily and after generation delete that. You should change some code to escape errors on generated files (controller and views) to remove references to that fake variable. And you should be more careful, because, you could update or delete some other record instead needed one

    Update

    Assuming that the DB structure is like this one and you should generate CRUD for the table 'othertable', you can:

    1. add PK as "id" to the table
    2. regenerate model "Othertable"
    3. generate CRUD for "othertable"
    4. Remove id from table
    5. Regenerate "Othertable"
    6. Add these lines to "Othertable":

      
      //imitate id
      public $id; 
      
      //rediclare init
      public function init() {
          parent::init();
          $this->id= $this->sometable_id; 
      }
      
      // Rediclare primary key. For this condition sometable_id 
      // have chosen as primary
      // key. We can change it
      public static function primaryKey() {
          return ['sometable_id'];
      }
      
    7. Remove id from OthertableSearch model

    8. Change findModel($id) method on OthertableController as:

     protected function findModel($id)
        {
            if (($model = Othertable::find()->where(['sometable_id'=>$id])->one()) !== null) {
                $model->id=$model->sometable_id;
                return $model;
            }
    
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    

    Attentions

    In this example I used sometable_id of the "othertable" assuming that there is only one record on the table with this sometable_id value (a.g. unique), otherwise every time you can get first record and change/delete that instead needed one. It can be changed to other unique variable(s) of the table. If you want use other variable, you should change on model and on findModel() method of the controller.