我有一个带构造函数的Eloquent模型(如下),它接受$type
参数。它们的类型是——比方说——first
、second
或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);
}
?>
正如您在上面的代码中看到的那样,我将模型的$table
属性设置为my_[type]_table
,因此我可以动态地使用3个可用表中的一个来使用模型。这样的:// Somewhere in controller
$type = 'first';
$myModel = new MyModel($type);
$myModel->create(.....); // <= Error is thrown here
问题是当Eloquent试图为表创建时间戳时,它不再关心我在__construct()
中设置的表名,它试图为表创建名为my_models
的时间戳(这显然是基于模型的类名),而不是为(在这种情况下)my_first_table
:
SQLSTATE[HY000]: error: 1 no such table: my_models (SQL:在"my_models" ("updated_at", "created_at")中插入值(2015-07-17 08:35:13, 2015-07-17 08:35:13))
是否有办法为自动创建时间戳保留动态表名?
当您调用$myModel->create()时,将创建一个新对象,并且不会将类型传递给它的构造函数。
只需将$type传递给$myModel->create()作为属性之一,更新构造函数:
public function __construct($attributes = array()) {
if (array_key_exists('type', $attributes)) {
$this->table = 'my_' . $attributes['type'] . '_model';
}
parent::__construct(array_except($attributes, 'type'));
}
有点晚了
<?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' );
}
}
?>