我正在使用 laravel eloquent 数据对象来访问我的数据,命名我的表、列、外键/主键等的最佳方式是什么?
我发现,那里有很多命名约定。我只是想知道哪一个最适合 laravel eloquent 模型。
我正在考虑以下命名约定:
- 单数表名(例如:Post)
- 单列名称(例如:userId - post 表中的用户 ID)
- 表格名称中多个单词的驼峰式大小写(例如:PostComment、PostReview、PostPhoto)
- 列名称中多个单词的驼峰式大小写(例如:firstName、postCategoryId、postPhotoId)
因此,我可以在 Controller 中使用类似的语法。
$result = Post::where('postCategoryId', '4')->get();
是否有任何推荐的 Laravel 指南?我可以继续使用这些命名约定吗?
如果有人有更好的建议,我会很高兴听到他们。非常感谢!
最佳答案
Laravel 有自己的命名约定。例如,如果您的模型名称是 User.php
那么 Laravel 期望类“User”在该文件中。它还需要 users
表用于 User
模型。但是,您可以通过在模型上定义表属性来覆盖此约定,例如,
class User extends Eloquent implements UserInterface, RemindableInterface {
protected $table = 'user';
}
来自 Laravel 官方文档:
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
一样蛇形,以便在关系的情况下自动使用它。同样,您可以通过在关系函数中指定其他参数来覆盖此约定。例如,
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');
}
}
Docs for Laravel eloquent relationship
对于表中的其他列,您可以随意命名。
我建议您阅读一次文档。
关于php - Laravel - 数据库、表和列命名约定?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25927700/