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

前端 未结 5 1529
借酒劲吻你
借酒劲吻你 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条回答
  •  Happy的楠姐
    2020-12-15 12:03

    I needed to change the table name based on my request (my tables would have a prefix based on my request). what I did was that I extended the Model class as MyModel, then I overrode the construct method, combining a table name based on my request and the default table name I provided my models.

    class MyModel extends Model
    {
    
      public function __construct(array $attributes = [])
      {
          parent::__construct($attributes);
          $this->setTable(Config::get('tablePrefix').$this->getTable());
      }
    }
    

    which you should replace the Config table prefix towards your approach.

    and then in my models I just extended MyModel and all was fine including static calls as I tested.

    class Category extends MyModel
    {
    
      protected $table = "categories";
    }
    

    So as my request changed I changed the Config I had provided and could get different table names such as a__categories, b__categories and all was fine including static calls, relations and saving to database.

提交回复
热议问题