2015-07-11 110 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"; 
} 
相關問題