我有一个带有构造函数的 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张 table 可用。像这样:
// Somewhere in controller
$type = 'first';
$myModel = new MyModel($type);
$myModel->create(.....); // <= Error is thrown here
问题是当 Eloquent 尝试为表创建时间戳时,它不再关心我在 __construct()
中设置的表名,它会尝试为名为 my_models
的表创建时间戳(这显然基于模型的类名),而不是为(在本例中)my_first_table
创建时间戳:
SQLSTATE[HY000]: General error: 1 no such table: my_models (SQL: insert into "my_models" ("updated_at", "created_at") values (2015-07-17 08:35:13, 2015-07-17 08:35:13))
有什么方法可以保留自动创建时间戳的动态表名?我在 Laravel 5.1 上。
最佳答案
当您调用 $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 - 创建时间戳会在构造函数中设置动态表名的模型引发错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31471802/