如何通过laravel创建数据透视表

问题描述 投票:29回答:4

在Laravel 4中,当使用http://four.laravel.com/docs/eloquent#many-to-many中描述的多对多关系时,我怎样才能让Laravel为我创建数据透视表?

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

到目前为止我所做的就是将belongsToMany信息添加到两个相应的模型中,即

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

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

laravel pivot-table laravel-4 eloquent
4个回答
50
投票

看起来好像需要手动创建数据透视表(即Laravel不会自动执行此操作)。这是怎么做的:

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

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

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

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

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


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

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

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

33
投票

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

然后你可以使用这个工匠命令:

php artisan generate:pivot table_one table_two

20
投票

扩展Ben的答案(我试图编辑它,但审稿人说它增加了太多):

要添加外键约束,请确保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');
    });
}

8
投票

对于多对多关系,您可以手动创建数据库的迁移文件,如下所示:

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');
    }
}

注意:如果你在数据透视表上有timestamps,你必须在两端的关系上设置withTimestamps,如下所示:

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

.

return $this->belongsToMany(\Mega\Modules\Account\Models\Account::class)->withTimestamps();
© www.soinside.com 2019 - 2024. All rights reserved.