Laravel如何创建数据透视表? [英] How is a pivot table created by Laravel?

查看:37
本文介绍了Laravel如何创建数据透视表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Laravel 4中,按 4.2文档,我实际上如何让Laravel为我创建数据透视表?

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如何知道要创建数据透视表?

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?

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

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

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?

推荐答案

似乎需要手动创建数据透视表(即Laravel不会自动创建).操作方法如下:

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:

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

1.) Create a new migration, using singular table names in alphabetical order (default):

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

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

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

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

3.)如果需要,添加外键约束. (我还没到那一点儿.)

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

现在,使用beta中的键来播种(例如)alpha表,您可以在AlphaTableSeeder中执行以下操作:

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

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

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

这篇关于Laravel如何创建数据透视表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆