Laravel 如何创建数据透视表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15821822/
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-09 02:25:05  来源:igfitidea点击:

How is a pivot table created by Laravel?

laravelpivot-tablelaravel-4eloquent

提问by Ben

In Laravel 4, when working with many-to-many relationships as described in the 4.2 docs, how can I actually get Laravel to create the pivot table for me?

在 Laravel 4 中,当处理4.2 文档中描述的多对多关系时,我如何才能真正让 Laravel 为我创建数据透视表?

Do I need to add something in my migrations for the two models that are involved? Do I need to manually create a migration for the pivot table? Or how does Laravel know to create the pivot table?

我是否需要在迁移中为涉及的两个模型添加一些内容?我是否需要手动为数据透视表创建迁移?或者 Laravel 如何知道创建数据透视表?

All I've done so far is add the belongsToManyinformation to the two respective models, i.e.

到目前为止我所做的只是将belongsToMany信息添加到两个各自的模型中,即

class User extends Eloquent 
{
    public function roles()
    {
         return $this->belongsToMany('Role');
     }
 }

However, that does not trigger creation of the pivot table. What step am I missing?

但是,这不会触发数据透视表的创建。我错过了什么步骤?

回答by Ben

It appears as though the pivot table does need to be created manually (i.e. Laravel does not do this automatically). Here's how to do it:

看起来好像确实需要手动创建数据透视表(即 Laravel 不会自动创建)。这是如何做到的:

1.) Create a new migration, using singulartable names in alphabeticalorder (default):

1.) 创建一个新的迁移,按字母顺序使用单数表名(默认):

php artisan make:migration create_alpha_beta_table --create --table=alpha_beta

2.) Inside the newly created migration, change the up function to:

2.) 在新创建的迁移中,将 up 函数更改为:

public function up()
{
    Schema::create('alpha_beta', function(Blueprint $table)
    {
        $table->increments('id');
        $table->integer('alpha_id');
        $table->integer('beta_id');
    });
}

3.) Add the foreign key constraints, if desired. (I haven't gotten to that bit, yet).

3.) 如果需要,添加外键约束。(我还没有达到那个程度)。



Now to seed, say, the alpha table, using keys from beta, you can do the following in your AlphaTableSeeder:

现在要播种 alpha 表,使用 beta 中的键,您可以在 AlphaTableSeeder 中执行以下操作:

public function run()
{
    DB::table('alpha')->delete();

    Alpha::create( array( 
        'all'           =>  'all',
        'your'          =>  'your',
        'stuff'         =>  'stuff',
    ) )->beta()->attach( $idOfYourBeta );
}

回答by user3260759

I use Jeffrey Way's Laravel-4-Generatorsor Laravel-5-Generators-Extended.

我使用 Jeffrey Way 的Laravel-4-GeneratorsLaravel-5-Generators-Extended

then you can just use this artisan command:

那么你可以使用这个 artisan 命令:

php artisan generate:pivot table_one table_two

回答by AfzalivE

To expand on Ben's answer (I tried to edit it but reviewers said it added too much):

为了扩展 Ben 的答案(我试图对其进行编辑,但评论者说它添加了太多):

To add the foreign key constraints, make sure if alpha id is unsigned, alpha_id is also unsigned in the pivot table. This migration would run after (2) in Ben's answer since it alters the table created then.

要添加外键约束,请确保 alpha id 是无符号的,alpha_id 在数据透视表中也是无符号的。此迁移将在 Ben 的答案中的 (2) 之后运行,因为它会更改当时创建的表。

public function up()
{
    Schema::table('alpha_beta', function(Blueprint $table)
    {
        $table->foreign('alpha_id')->references('id')->on('alpha');
        $table->foreign('beta_id')->references('id')->on('beta');
    });
}

回答by Mahmoud Zalt

For Many to Many relationships you can create the Migration file of the Database manually like this:

对于多对多关系,您可以像这样手动创建数据库的迁移文件:

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;

class CreateAccountTagTable extends Migration
{

    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('account_tag', function (Blueprint $table) {
            // $table->timestamps(); // not required
            // $table->softDeletes(); // not required

            $table->integer('account_id')->unsigned();
            $table->foreign('account_id')->references('id')->on('accounts');

            $table->integer('tag_id')->unsigned()->nullable();
            $table->foreign('tag_id')->references('id')->on('tags');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('account_tag');
    }
}

Note: in case you have timestampson the pivot table you must set withTimestampson the relationship of both ends like this:

注意:如果你timestamps在数据透视表上,你必须withTimestamps像这样设置两端的关系:

return $this->belongsToMany(\Mega\Modules\Account\Models\Tag::class)->withTimestamps();

.

.

return $this->belongsToMany(\Mega\Modules\Account\Models\Account::class)->withTimestamps();

回答by Adam Pery

  1. Create new migration:
  1. 创建新迁移:
php artisan make:migration create_alpha_beta_table --create=alpha_beta
  1. Inside the newly created migration:
  1. 在新创建的迁移中:
public function up() {
    Schema::create('alpha_beta', function(Blueprint $table) {
            $table->increments('id');
            $table->unsignedBigInteger('alpha_id');
            $table->unsignedBigInteger('beta_id');
            // foreign keys
            $table->foreign('alpha_id')->references('id')->on('alphas');
            $table->foreign('beta_id')->references('id')->on('betas');
     });
}