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

查看:30
本文介绍了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).

现在要播种 alpha 表,使用 beta 中的键,您可以在 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天全站免登陆