php - Laravel - 数据库、表和列命名约定?

标签 php database laravel naming-conventions eloquent

我正在使用 laravel eloquent 数据对象来访问我的数据,命名我的表、列、外键/主键等的最佳方式是什么?

我发现,那里有很多命名约定。我只是想知道哪一个最适合 laravel eloquent 模型。

我正在考虑以下命名约定:

  1. 单数表名(例如:Post)
  2. 单列名称(例如:userId - post 表中的用户 ID)
  3. 表格名称中多个单词的驼峰式大小写(例如:PostComment、PostReview、PostPhoto)
  4. 列名称中多个单词的驼峰式大小写(例如: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/

相关文章:

ruby-on-rails - 什么数据库用于 15M 记录和快速搜索索引

laravel - 仅显示可见的项目和组中有项目的组

php - 如何在同一文本框中输入占位符和值

php - 如何使用 PHP 在 URL 中传递 URL(作为 GET 参数)?

mysql - SQL音乐播放列表数据库查询设计

php - 关于允许用户向 mysql 数据库提交信息的指南

php cURL 问题

php - SQL查找VARCHAR类型列中的最大数

javascript - Laravel 项目 : force webpack to ignore some files

mysql - laravel 所见即所得编辑器 - 将 html 保存到数据库