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

前端 未结 5 1530
借酒劲吻你
借酒劲吻你 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 11:48

    this should work with static methods also (only tested on 5.7)

    use Illuminate\Database\Eloquent\Model;
    
    function makeModel($table)
    {
        $model = new class extends Model
        {
            public static $entryTable;
    
            public function setTable($table)
            {
                $this->table = static::$entryTable = $table;
            }
    
            public static function __callStatic($method, $parameters)
            {
                $static = (new static);
                $static->setTable($static::$entryTable);
    
                return $static->$method(...$parameters);
            }
        };
        $model->setTable($table);
    
        return $model;
    }
    

提交回复
热议问题