2015-07-11 106 views
0

雄辩有关于数据库表中的一些假设。全局配置Eloquent的正确方法是什么?

  • 它使用表名的复数名称类。我使用单数名词来表名。
  • 默认情况下,雄辩预计created_atupdated_at列。我用cDatauDate
  • 我用驼峰命名不列underline_separated名。

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

回答

0

而是扩展Model类的创建例如MyModel和设置您的属性有一个新的类。然后扩展MyModel

0

的最好方法是创建一个扩展雄辩你自己的基本模型。然后,你可以为时间戳列定义新的价值观和覆盖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 
+0

谢谢,列名怎么样?我使用camelCase命名列不是underline_separated名称。 – PHPst

+0

我不认为你需要做任何特别的事情。您可以添加'public static $ snakeAttributes = true;',但仅用于关系名称和增变器缓存。 – lukasgeiter

0

您可以通过编辑供应商做到这一点\框架\ 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"; 
} 
相关问题