php - Creating timestamps throws an error for model with dynamic table name set in constructor -


i have eloquent model constructor (below), takes $type param. types - let's - first, second or third.

<?php  namespace app;  use illuminate\database\eloquent\model;  class mymodel extends model {      protected $table; // define $table field      public function __construct($type = null, array $attributes = array()) {          // initialize $table field         $this->table = isset($type) ? 'my_'.$type.'_table' : null;          parent::__construct($attributes);     }  ?> 

as can see in code above, set model's $table property my_[type]_table, can use model dynamically 1 of 3 tables available. this:

// somewhere in controller $type = 'first'; $mymodel = new mymodel($type); $mymodel->create(.....); // <= error thrown here 

the problem is when eloquent tries create timestamps table, doesn't care anymore table name set in __construct() , tries create timestamps table called my_models (which based on model's class name), instead of doing (in case) my_first_table:

sqlstate[hy000]: general error: 1 no such table: my_models (sql: insert "my_models" ("updated_at", "created_at") values (2015-07-17 08:35:13, 2015-07-17 08:35:13))

any way keep dynamic table name automatic timestamps creation? im on laravel 5.1.

when call $mymodel->create(), new object created , type not passed constructor.

just pass $type $mymodel->create() 1 of attributes, update constructor:

public function __construct($attributes = array()) {   if (array_key_exists('type', $attributes)) {     $this->table = 'my_' . $attributes['type'] . '_model';   }    parent::__construct(array_except($attributes, 'type')); } 

and should work.


Comments