Php Laravel使用自定义foregin键保存关系

Php Laravel使用自定义foregin键保存关系,php,laravel,Php,Laravel,在我的web应用程序中,我必须以schedule\u instagram\u accounts和actions\u logs的形式提交表格 每行操作日志都属于带有schedule\u id外键的schedule\u instagram\u accounts表 附表\u instagram\u账户: 操作日志: 操作日志模型: 时间表\ instagram\账户模式: 现在,我想将数据保存到与schedule\u instagram\u accounts表链接的具有关系的actions\u日志中

在我的web应用程序中,我必须以schedule\u instagram\u accounts和actions\u logs的形式提交表格

每行操作日志都属于带有schedule\u id外键的schedule\u instagram\u accounts表

附表\u instagram\u账户:

操作日志:

操作日志模型:

时间表\ instagram\账户模式:

现在,我想将数据保存到与schedule\u instagram\u accounts表链接的具有关系的actions\u日志中

我得到这个错误:

SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: 
a foreign key constraint fails 
(`instacheeta`.`actions_logs`, CONSTRAINT `actions_logs_schedule_id_foreign` 
FOREIGN KEY (`schedule_id`) 
REFERENCES `instagram_actions_histories` (`id`) ON DELETE CASCADE) 

(SQL: insert into `actions_logs` (`schedule_id`, `action_type`, `log`, `updated_at`, `created_at`) values (1, 1, eeeeeeeee, 2018-07-11 09:12:55, 2018-07-11 09:12:55))
更新:

但是这个代码很好用:

ActionsLog::create([
    'schedule_id' => '1',
    'action_type' => 1,  //like
    'log' => 'qqqqqqq'
]);

您在外键约束定义中出错:

这一行:

$table->foreign('schedule_id')->references('id')->on('instagram_actions_histories')->onDelete('cascade');
应该是:

$table->foreign('schedule_id')->references('id')->on('schedule_instagram_accounts')->onDelete('cascade');
还有一件事,Laravel足够聪明,可以为您填充外键,因此您必须这样做:

ScheduleInstagramAccounts::find(1)->log()->create([
    'action_type' => 1,
    'log' => 'test'
]);

您可以添加与schedule\u instagram\u accounts的关系,但在表actions\u中,instagram\u actions\u histories表中记录外键。我认为这是个问题。试试这个:

InstagramActionsHistories::find(1)->log()->create([
   'schedule_id' => 1,
   'action_type' => 1,
   'log' => 'test'
])
或者这个:

ActionsLog::create([
   'schedule_id' => 1,
   'action_type' => 1,
   'log' => 'test'
]);

instagram\u actions\u History有1个id?@J.Doe是的,我在表中有,更新的内容是一个很大的错误:
$table->foreign('schedule_id')->references('id')->on('instagram_actions_histories')->onDelete('cascade');
$table->foreign('schedule_id')->references('id')->on('schedule_instagram_accounts')->onDelete('cascade');
ScheduleInstagramAccounts::find(1)->log()->create([
    'action_type' => 1,
    'log' => 'test'
]);
InstagramActionsHistories::find(1)->log()->create([
   'schedule_id' => 1,
   'action_type' => 1,
   'log' => 'test'
])
ActionsLog::create([
   'schedule_id' => 1,
   'action_type' => 1,
   'log' => 'test'
]);