Update the table name at runtime not working - laravel Eloquent ORM

前端 未结 5 1528
借酒劲吻你
借酒劲吻你 2020-12-15 11:15

This is my model:

class Product extends \\GlobalModel {
    protected $table = \'product\';
}

I want to update the table name oops_

5条回答
  •  轮回少年
    2020-12-15 12:04

    The problem with the accepted answer is, that modifying the retrieved model instance and later on saving it won't work. See my comment above.

    The following trait allows for passing on the table name during hydration.

    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;
        }
    
    }
    

    Here is how to use it:

    class Product extends Model
    {
        use BindsDynamically;
    }
    

    Applied to the accepted answer:

    $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
    

提交回复
热议问题