laravel-4 - 在 migrate laravel 中的同一张表上创建多个外键

标签 laravel-4

    Schema::table('performance', function($table)
    {
        $table->foreign('song_id')
                ->references('id')
                ->on('songs')
                ->onDelete('cascade');
    });
    Schema::table('performance', function($table)
    {
        $talbe->foreign('artist_id')
                ->references('id')
                ->on('artists')
                ->onDelete('cascade');  
    });

我收到一个错误: “在非对象上调用成员函数 foreign()” .

最佳答案

相反,您不能对外键使用多个命令。您只需要一个外键命令并组合您要定义的所有行。这是您应该运行的代码。

Schema::table('performance', function (Blueprint $table)
        {
            $table->unsignedInteger('song_id');
            $table->unsignedInteger('artist_id');
            $table->foreign(['song_id','artist_id'])->references(['id','id'])
                  ->on(['song','artists'])->onDelete(['cascade','cascade']);
        });

如果不行(之前的 Laravel 版本可能不行),我们可以用普通的 SQL 语句添加其他外键。
Schema::table('performance', function (Blueprint $table)
        {
            $table->unsignedInteger('song_id');
            $table->unsignedInteger('artist_id');
            $table->foreign('song_id')->references('id')
                  ->on('song')->onDelete('cascade');
        });
DB::statement(
    "ALTER TABLE performance ADD FOREIGN KEY (artist_id) REFERENCES artists(id) ON DELETE CASCADE"
);

希望能帮助到你!

关于laravel-4 - 在 migrate laravel 中的同一张表上创建多个外键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27010263/

相关文章:

php - 重定向更改 Laravel 4 中 Auth::check() 的状态

laravel-4 - Laravel Eloquent ORM 组在哪里

javascript - 在 Laravel 4 中使用 jquery Ajax

laravel - 首先 Eloquent 或创建文档或用法

php - 如何使用 laravel 中的验证使输入日期字段大于或等于另一个日期字段

mysql - Laravel Schema Builder 改变存储引擎

php - laravel 4.2 对复杂查询进行分页

php - 在 Supervisord 和 HHVM 中使用 Laravel Queue 会导致 tmp 文件夹中有很多 .map 文件

php - 如何在 IIS 7.5 上设置 Laravel 项目?

php - Laravel 4 中的 Eloquent 调用 : Dealing with single columns over multiple tables