Reading from Database View but Writing to Table

I have a model which pulls data from a database view. The reason is because it provides a number of calculated stats I do not want to do in PHP. This is working great, however, this model needs to be able to handle inserts, updates and deletes.

Since the name of the database "object" comes from the method tableName, I can only have one set at a time (either the view or the table). Since the method tableName gets invoked immediately on the model creation, I cannot seem to find a way to detect whether the table or view is needed an return the proper string.

How can I accomplish reading from the view but writing/deleting on the table?

I think you have to have different models for view and for tables. For example you can have MyDataView model class for view and MyData and MyDataExt for models.

When you need to display data, for example, in grid or list view you can use MyDataView model and when you do updates then use table-based models.

Thank you, that helped. I had that thought in my head, but it just did not gel into something workable. I left the model the way it was with tableName=DB_table for doing the CUD (of CRUD). I created a second model that extended the first one that simply had tableName=DB_view. I then used the base model for create/update/delete and the extended model for admin/view. This all worked well, except for "view". Even though I specified the DB_view model, it still complained that it could not find the fields the DB_view adds. Here is sample code:

controller:


   public function actionView($id) {

      $this->layout = 'plain';

      $this->render('view',array(

         'model'=>$this->loadModel($id),

      ));

   }


   public function loadModel($id) {

      $model=Publisher_R::model()->findByPk($id); /* NOTE THAT Publisher_R is the extended model */

      if($model===null)                           /* which refers to the DB_view                 */

         throw new CHttpException(404,'The requested page does not exist.');

      return $model;

   }  

views/xxx/view.php:


   $this->widget('zii.widgets.CDetailView', array(

        'data'=>$model,

        'attributes'=>array(

                'nProductID',     /* Regular DB field */

                'strProductCode', /* Regular DB field */

                'strSKU',         /* Regular DB field */

                'strTitle',       /* Regular DB field */

                'nPCount',        /* Provided by view field <-- throws error "not found" */

        ),

   ));

It should work, so re-check your code and also try to execute a ‘select * from’ query to your view from some MySQL tool - does the ‘nPCount’ field returned by this statement?

You can also refer to my post - see "MySQL VIEWs" section and links to the code on github. In my case I do not inherit the view-based model from the table-based model, but I think inheritance should also work.