全局配置Eloquent的正确方法是什么?


What is the correct way of configing Eloquent globally?

Eloquent有一些关于db表的假设。

  • 使用类的复数名作为表名。我使用单数名词作为表名。
  • 缺省情况下,Eloquent期望created_atupdated_at列。我使用cDatauDate
  • 我使用camelCase来命名列而不是下划线分隔的名称。

我知道可以使用类属性来覆盖这些。全局配置的正确方法是什么?

不要扩展Model类,而是创建一个新类,例如MyModel,并在那里设置属性。然后扩展MyModel

最好的方法是创建您自己的扩展Eloquent的基本模型。然后可以为时间戳列定义新值并覆盖getTable()方法:

class BaseModel extends Model {
    const CREATED_AT = 'cData';
    const UPDATED_AT = 'uData';
    /**
     * Get the table associated with the model.
     *
     * @return string
     */
    public function getTable()
    {
        if (isset($this->table)) return $this->table;
        return str_replace('''', '', snake_case(class_basename($this)));
    }
}

然后,让你所有的模型扩展那个基本模型:

class User extends BaseModel

您可以通过编辑vendor'framework'src'Illuminate'Database'Eloquent'Model.php文件来实现。

/**
 * The name of the "created at" column.
 *
 * @var string
 */
const CREATED_AT = 'cDate';
/**
 * The name of the "updated at" column.
 *
 * @var string
 */
const UPDATED_AT = 'uDate';
/**
 * The name of the "deleted at" column.
 *
 * @var string
 */
const DELETED_AT = 'dDate';

但老实说,编辑核心源代码并不是一个好主意。你可以通过

class MyModel extends Model {
     /**
     * The name of the "created at" column.
     *
     * @var string
     */
    const CREATED_AT = 'cData';
      /**
     * The name of the "updated at" column.
     *
     * @var string
     */
    const UPDATED_AT = 'uData';
     /**
     * The name of the "deleted at" column.
     *
     * @var string
     */
     const DELETED_AT = 'dDate';
}

现在写你的模型扩展MyModel而不是原来的Model。例如:

class User extends MyModel{
    //Yes, if you want to change default table name then you should do this. Shouldn't be global. 
    protected $table = "user";
}