在运行时更新表名称不起作用 - laravel Eloquent ORM

aka*_*ani 8 model eloquent laravel-4

这是我的模特:

class Product extends \GlobalModel {
    protected $table = 'product';
}
Run Code Online (Sandbox Code Playgroud)

我想在运行时更新表名oops_product而不是product.

我找到了getTable(); 从模型中获取表名称及其工作正常:

$tableName = with(new Product)->getTable();
Run Code Online (Sandbox Code Playgroud)

但是当我使用setTable()设置表名时; 根据GitHub解决方案,它不更新表名.

with(new Product)->setTable("oops_produdct");
Run Code Online (Sandbox Code Playgroud)

有什么不对的吗?

帮助将不胜感激.

编辑:

$product = new Product(); 
$product->getTable(); // output: product 
$product->setTable("oops_product"); 
$product->getTable(); // output: oops_product 
Run Code Online (Sandbox Code Playgroud)

现在,当我运行这个

$product->all(); 
Run Code Online (Sandbox Code Playgroud)

它执行

"select * from product" 
Run Code Online (Sandbox Code Playgroud)

代替

"select * from oops_product"
Run Code Online (Sandbox Code Playgroud)

Jar*_*zyk 15

all()是一种静态方法,它使用全新的实例并对其进行调用get().

所以你需要的只是使用正确的方法:

$product = new Product;
$product->getTable(); // products
$product->setTable('oooops');
$product->get(); // select * from oooops
$product->first(); // select * from oooops limit 1
etc...
Run Code Online (Sandbox Code Playgroud)

只是避免使用静态Eloquent方法,因为它们显然会创建具有默认table属性的新实例.


Ste*_*fan 6

可接受的答案的问题在于,修改检索到的模型实例并在以后保存它不起作用。请参阅上面的评论。

以下特征允许在水合期间传递表名。

trait BindsDynamically
{
    protected $connection = null;
    protected $table = null;

    public function bind(string $connection, string $table)
    {
        $this->setConnection($connection);
        $this->setTable($table);
    }

    public function newInstance($attributes = [], $exists = false)
    {
        // Overridden in order to allow for late table binding.

        $model = parent::newInstance($attributes, $exists);
        $model->setTable($this->table);

        return $model;
    }

}
Run Code Online (Sandbox Code Playgroud)

使用方法如下:

class Product extends Model
{
    use BindsDynamically;
}
Run Code Online (Sandbox Code Playgroud)

应用于接受的答案:

$product = new Product;
$product->getTable(); // products
$product->bind('connection', 'oooops');
$product->get(); // select * from oooops
$product->first(); // select * from oooops limit 1
etc...
$product->myTestProp = 'test;
$product->save(); // now saves into oooops
Run Code Online (Sandbox Code Playgroud)