在Laravel 4中,当处理the 4.2 docs中描述的多对多关系时,我如何让Laravel为我创建数据透视表?

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

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

但是,这不会触发数据透视表的创建.我错过了哪一步?

推荐答案

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.) 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函数更改为:

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).


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相关问答推荐

在Laravel Lumen中迭代连接查询数据

当未通过验证的字段是值数组时,Laravel$validator->;validator()方法不会引发异常

将数据从控制器传递到 Laravel 中的视图

如何处理 Laravel 的 SMTP 驱动程序中的自签名 TLS 证书?

查询构建器中的 Laravel 5 多重 Select ()

laravel:如何在 Eloquent Query 中使用 LOWERCASE 函数?

Laravel 5.4 LengthAwarePaginator

合并和排序两个 Eloquent 集合?

约定表名(带下划线)

我如何从给定的日期时间 struct 创建Carbon 对象?

测试指向外部站点的重定向链接

Laravel 应用程序连接数据库时速度很慢

Laravel 获取文件内容

如何在 Laravel 测试中禁用选定的中间件

Laravel binding绑定的用途和目的是什么?

如何判断 Laravel 集合是否为空?

php artisan migrate - SQLSTATE [HY000] [1045] 用户'laravel'@'localhost'的访问被拒绝

如何在 Laravel 5 请求类中使用有时规则

Laravel 4:分析器在哪里?

Laravel 5 Illuminate\Http\Request 的方法不允许静态调用