$ this-> setTable()在Model中不起作用

问题描述 投票:0回答:2

我是laravel的新手。我想在模型的构造函数中将表名更改为给定的字符串。下面的代码是我尝试过的,但它似乎无法正常工作。

任何建议或意见将不胜感激。

谢谢

模型

class Custom extends Model
{
protected $guarded = ['id', 'ct'];

const UPDATED_AT = null;
const CREATED_AT = 'ct';

public function __construct(array $attributes = [], string $tableName = null) {

    parent::__construct($attributes);

    $this->setTable($tableName);
}

}

调节器

$tableName = 'some string';
$custom = new Custom([], $tableName);
$result = $custom->create($data);
php laravel laravel-5
2个回答
2
投票

您只在构造函数上传递一个参数,但它需要2个参数。所以,要么传递两个参数,要么像这样制作构造函数 -

public function __construct($table = null, $attr = [])
{
    $this->setTable($table);
    parent::__construct($attributes);
}

但我不明白你为什么这样做?标准做法是为每个表创建一个模型。你应该这样做。


0
投票

没有Model :: create方法。这是通过Model::__call神奇的恶作剧。调用$custom->create(...)会将调用转发给调用Builder::createBuilder::newModelInstanceModel::newInstance又调用$data。这段代码根本不知道原始模型,它只知道Model::create(...)属性。 (它通常在静态上下文中调用,如class Custom2 extends Custom { public $table = 'some string'; } ,没有原始实例。)

最简单的解决方法是创建一个派生自Custom的新类,并让它声明$ table属性。这将需要每个表一个模型。

qazxswpoi
© www.soinside.com 2019 - 2024. All rights reserved.