database 迁移中的 Laravel 关系?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13541057/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 08:47:32  来源:igfitidea点击:

Laravel relationships in migrations?

databasemigrationrelationshiplaravel

提问by qwerty

I know you can define table relationships fairly easy with $this->belongs_to(), $this->has_many()etc, but what i don't understand is how the relationship table is created; the table that binds the two tables together (i forgot what the term is called).

我知道你可以很容易地定义表关系$this->belongs_to()$this->has_many()等等,但我不明白关系表是如何创建的;将两个表绑定在一起的表(我忘记了这个术语叫什么)。

Let's say i'm creating a users table. I want that user to belong to a certain "Role". There are multiple roles, and every role can have multiple users. I will need to also create a rolestable for that. So far, so good.

假设我正在创建一个用户表。我希望该用户属于某个“角色”。有多个角色,每个角色可以有多个用户。我还需要为此创建一个roles表。到现在为止还挺好。

But after reading the documentation, it says i should add the $this->belongs_to()in the model, not the migration itself. When, and how is the relationship table created? If i create the rolesand userstables, and add $this->belongs_to('roles')to the usersmodel, and $this->has_many('users')to the rolesmodel, will the middle table be created automatically?

但是在阅读文档后,它说我应该$this->belongs_to()在模型中添加,而不是迁移本身。何时以及如何创建关系表?如果我创建rolesusers表,并添加$this->belongs_to('roles')users模型,并$this->has_many('users')roles模型中,将中间表自动创建?

采纳答案by gregchapple

As far as I know, no relationship table will be created. What you will need to do is have a role_idon your userstable, so that when you create a user, the ID of the role will be stored there. This will enable you do select all users where role_id == '1'or whatever it may be. For example:

据我所知,不会创建关系表。你需要做的是role_id在你的users表上有一个,这样当你创建一个用户时,角色的 ID 将被存储在那里。这将使您能够选择所有用户所在的位置role_id == '1'或位置。例如:

$admins = User::where('role_id', '=', 1);

Where on the ROLEStable the record with ID='1'is admin. So again to answer your question, no relationship table is created, instead the relationship exists within your two tables in the form of a role_idcolumn for each user. Out of interest, are you using foreign keys?

凡在ROLES表记录ID='1'为admin。所以再次回答你的问题,没有创建关系表,而是在你的两个表中role_id以每个用户的列的形式存在关系。出于兴趣,您是否使用外键?

If you want to have a relationships table you could create one called user_rolesor something and store the role_idand user_idin there, however I think its easier to use the above method as then you can use all the Laravel/Eloquent goodness.

如果你想有一个关系表,你可以创建一个名为user_roles或东西,存储role_iduser_id在那里,但我认为它更容易使用上面的方法,那么你可以使用所有的Laravel /雄辩善良。

Hope this helps :)

希望这可以帮助 :)

回答by Roark

When creating a migration you can specify foreign keys on your tables, i.e.

创建迁移时,您可以在表上指定外键,即

public function up()
{
    Schema::table('roles', function(Blueprint $table) {
        $table->increments('id');
        $table->integer('user_id')->unsigned();
        //rest of fields then...
        $table->foreign('user_id')->references('id')->on('users');
    });
}

This will create a foreign key on the user_id column on the roles table. The benefits of foreign keys is that when an update or delete is made the foreign key table will be automatically updated or "cascaded" great description found here

这将在角色表的 user_id 列上创建一个外键。外键的好处是,当进行更新或删除时,外键表将自动更新或“级联”在这里找到很好的描述

As described on the Laravel documentation you could also specify your cascading on update using the following syntax

如 Laravel 文档中所述,您还可以使用以下语法在更新时指定级联

$table->foreign('user_id')
  ->references('id')->on('users')
  ->onDelete('cascade');

I would do a bad job of trying to explain it better than the documentation does so please have a read through the "Relationships"section of the Eloquent ORM documentation to see how its done.

我会比文档更好地解释它做得不好,所以请通读Eloquent ORM 文档的“关系”部分,看看它是如何完成的。

回答by Mere Development

It looks like a few of the initial questions were never answered, i.e. "When, and how is the relationship table created" & "will the middle table be created automatically":

看起来一些最初的问题从未得到回答,即“何时以及如何创建关系表”&“中间表是否会自动创建”:

As far as I am aware, these tables need to be created manually. So create the migration file like so:

据我所知,这些表需要手动创建。所以像这样创建迁移文件:

Laravel 5

Laravel 5

php artisan make:migration create_role_user_table

Laravel 4

Laravel 4

php artisan migrate:make create_role_user_table

Note that the names are singular, and are presented in alphabetical order.

请注意,名称是单数,并按字母顺序显示。

Then in the migration something like:

然后在迁移中类似:

public function up()
{
    Schema::create('role_user', function($table) {
        $table->increments('id');
        $table->integer('role_id');
        $table->integer('user_id');
        $table->timestamps();
    });
}

Hope that helps. I'm not sure if the timestamps are needed in Pivot Tables or not, so please experiment.

希望有帮助。我不确定数据透视表中是否需要时间戳,所以请进行试验。

回答by Ariful Haque

Though its an old Post, I though I can contribute something updated. For Laravel5, Jeffrey Wayhas developed a package Laravel5 Generators-extendedwhich enhance the generator capability of php artisanfor

虽然它是一个旧帖子,但我虽然可以贡献一些更新的东西。对于Laravel5,杰弗里的方式,制定了一系列Laravel5发电机扩展其增强的生成器功能php artisan

  • make:migration:schema
  • make:migration:pivot
  • make:seed
  • make:migration:schema
  • make:migration:pivot
  • make:seed

For many-to-many relation between users and role, you can just use

对于用户和角色之间的多对多关系,您可以使用

php artisan make:migration:pivot users role

and it will generate the required migration class. You don't need to code manually for this.

它将生成所需的迁移类。您不需要为此手动编码。

回答by pera

This video helped me.

这个视频帮助了我。

https://laracasts.com/series/laravel-5-fundamentals/episodes/14

https://laracasts.com/series/laravel-5-fundamentals/episodes/14

What was surprising for me was that only one side of the relationship needs pointer_id in migration table, not both. For example, if we have Author with many Articles, we only add

令我惊讶的是,关系中只有一侧需要迁移表中的 pointer_id,而不是两者。例如,如果我们有很多文章的作者,我们只添加

$table->integer('author_id')

to article migration and thats it.

到文章迁移,仅此而已。

回答by Lino

I know this is an old post but as I had the same question in mind. I've found the solution in the Laravel manual (5.0)where it is described that for this particular many-to-many relationship you can create the table manually and then declare the type of relationship into Model in this way:

我知道这是一个旧帖子,但因为我有同样的问题。我在Laravel 手册 (5.0)中找到了解决方案,其中描述了对于这种特定的多对多关系,您可以手动创建表,然后以这种方式将关系类型声明到 Model 中:

return $this -> belongsToMany('App\<Model>', '<table_created_manually>');

or if you want to use specific associated keys:

或者如果您想使用特定的关联键:

return $this -> belongsToMany('App\<Model>', '<rel_table1_table2>' '<table1>_id', '<table2>_id');

Hope this can help.

希望这能有所帮助。