問題描述
我正在使用 laravel eloquent 數(shù)據(jù)對象來訪問我的數(shù)據(jù),為我的表、列、外鍵/主鍵等命名的最佳方式是什么?
I'm using laravel eloquent data objects to access my data, what is the best way to name my tables, columns, foreign/primary keys etc?
我發(fā)現(xiàn),有很多命名約定.我只是想知道哪一種最適合 Laravel eloquent 模型.
I found, there are lots of naming conventions out there. I'm just wondering which one best suits for laravel eloquent models.
我正在考慮以下命名約定:
I'm thinking of following naming convention:
- 單一的表名(例如:Post)
- 單列名稱(例如:userId - 帖子表中的用戶 ID)
- 表格名稱中多個單詞的駝峰式大小寫(例如:PostComment、PostReview、PostPhoto)
- 列名稱中多個單詞的駝峰式大小寫(例如:firstName、postCategoryId、postPhotoId)
因此,我可以在控制器中使用類似的語法.
So with this, I could use similar syntax in the controller.
$result = Post::where('postCategoryId', '4')->get();
是否有任何推薦的 Laravel 指南?我可以繼續(xù)使用這些命名約定嗎?
Are there any recommended Laravel guidelines for this? Can I proceed with these naming conventions?
如果有人有更好的建議,我會很高興聽到的.非常感謝!
If someone has better suggestions, I will be very happy to hear them.Thanks a lot!
推薦答案
Laravel 有自己的命名約定.例如,如果您的模型名稱是 User.php
,那么 Laravel 期望類 'User' 位于該文件中.User
模型還需要 users
表.但是,您可以通過在模型上定義表屬性來覆蓋此約定,例如
Laravel has its own naming convention. For example, if your model name is User.php
then Laravel expects class 'User' to be inside that file. It also expects users
table for User
model. However, you can override this convention by defining a table property on your model like,
class User extends Eloquent implements UserInterface, RemindableInterface {
protected $table = 'user';
}
來自 Laravel 官方文檔:
From Laravel official documentation:
請注意,我們沒有告訴 Eloquent 將哪個表用于我們的 User 模型.類的小寫復數(shù)名稱將用作表名除非明確指定另一個名稱.所以,在這種情況下,Eloquent將假設 User 模型將記錄存儲在 users 表中.你可以指定一個通過在模型上定義 $table
屬性來自定義表
Note that we did not tell Eloquent which table to use for our User model. The lower-case, plural name of the class will be used as the table name unless another name is explicitly specified. So, in this case, Eloquent will assume the User model stores records in the users table. You may specify a custom table by defining a
$table
property on your model
如果您將在另一個表中使用用戶表 id 作為外鍵,那么它應該像 user_id
這樣的蛇形大小寫,以便它可以在關系的情況下自動使用.同樣,您可以通過在關系函數(shù)中指定附加參數(shù)來覆蓋此約定.例如,
If you will use user table id in another table as a foreign key then, it should be snake-case like user_id
so that it can be used automatically in case of relation. Again, you can override this convention by specifying additional arguments in relationship function. For example,
class User extends Eloquent implements UserInterface, RemindableInterface {
public function post(){
return $this->hasMany('Post', 'userId', 'id');
}
}
class Post extends Eloquent{
public function user(){
return $this->belongsTo('User', 'userId', 'id');
}
}
Laravel eloquent關系的文檔
對于表中的其他列,您可以隨意命名它們.
For other columns in table, you can name them as you like.
我建議您瀏覽一次文檔.
I suggest you to go through documentation once.
這篇關于Laravel - 數(shù)據(jù)庫、表和列命名約定?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!