php - Laravel 如何从非主键创建外键约束

标签 php mysql laravel laravel-5.5

我有一个名为header的表

$table->increments('id');
$table->integer('restaurant_number')->unsigned();
$table->integer('transaction_id')->unsigned()->unique(); <-- Right here

关于 docs它说

Laravel also provides support for creating foreign key constraints, which are used to force referential integrity at the database level. For example, let's define a user_id column on the posts table that references the id column on a users table:

但是在我的 details 表中,我引用了不是主键的 header 中的 transaction_id,我得到了这个错误 (errno: 150 "Foreign key constraint is incorrectly formed")。如何从非主要引用它

$table->increments('id');
$table->integer('restaurant_number')->unsigned();
$table->integer('transaction_id')->unsigned()->nullable();
$table->foreign('transaction_id')->references('transaction_id')->on('header');

最佳答案

也许问题是因为两个表的类型完全相同。我可以看到在第二个表中该字段可以为空,而在第一个表中则不能。也许这就是问题所在

关于php - Laravel 如何从非主键创建外键约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47446528/

相关文章:

php - 根据同一表中的其他值标记/更新值

PHP 密码无效,即使有效

php - PHP 中的生日倒计时计算器

php - 在php中保护数据库密码

php - 如何在数据库播种器中将参数传递给 laravel 工厂?

PHP:imagePNG() 不会将文件保存到目录。文件权限都正确,还是不行

php - mysqli::query 不返回 FALSE 或 mysqli_result - PHP 错误?

MySQL 认证指南练习 Qn - View 的列名

php - 在 Laravel 中创建 mysql 帐户用户和数据库

php - 如何修复在 Laravel 中找不到的类 'App\Http\Controllers\Notification'?