Creating timestamps generates an error for model with dynamic table name set in constructor
I have an Eloquent model with a constructor (below) that takes a $type
param parameter . Types - say - 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 you can see in the above code, I am setting a property on the $table
model my_[type]_table
, so I can dynamically use the model with one of the three tables available. Like this:
// Somewhere in controller
$type = 'first';
$myModel = new MyModel($type);
$myModel->create(.....); // <= Error is thrown here
Problem: when Eloquent tries to create timestamps for a table, now there is no value about the table name I set in __construct()
, and tries to create timestamps for the named table my_models
(which is obviously based on the model class name) instead of doing this (in this case) my_first_table
:
SQLSTATE [HY000]: general error: 1 no such table: my_models (SQL: insert into values "my_models" ("updated_at", "created_at") (2015-07-17 08:35:13, 2015-07-17 08 : 35: 13))
How to store dynamic table name to generate automatic timestamps? Im on Laravel 5.1.
source to share
When you call $ myModel-> create () , a new object is created and the type is not passed to its constructor.
Just pass $ type to $ myModel-> create () as one of the attributes, update the 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 it should work.
source to share
a little late
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class MyModel extends Model {
//-- using a mutator
public function setTypeAttribute($type)
{
//-- set type =)
$this->attributes['type'] = $type;
//-- then use this type for your table name convention
$this->setTable( 'my_'. $type .'_table' );
}
}
?>
source to share