I want to add an Api to my forum to add record in my database.
Error
[2022-09-07 11:45:03] flarum.ERROR: PDOException: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails (`web_fdev`.`st_invitations`, CONSTRAINT `st_invitations_invited_user_id_foreign` FOREIGN KEY (`invited_user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE) in /www/wwwroot/mysite.com/vendor/doctrine/dbal/lib/Doctrine/DBAL/Driver/PDOStatement.php:117
I know what this error means. However, I fully confirm that the data I sent does not violate the integrity constraint. I suspect that there is a problem when the system parses the data, so I want to know whether there is a problem in the way I save the data?
Controller
<?php
namespace TPam\SteveTribe\Controller\Api;
use Flarum\Http\RequestUtil;
use Tobscure\JsonApi\Document;
use Psr\Http\Message\ServerRequestInterface as Request;
use Flarum\Api\Controller\AbstractCreateController;
use TPam\SteveTribe\Model\Invitations;
use TPam\SteveTribe\Serializer\InvitedUserSerializer;
class AddAUsersController extends AbstractCreateController
{
public $serializer = InvitedUserSerializer::class;
protected function data(Request $request, Document $document)
{
$invitation = new Invitations;
$invitation->invitor_user_id = 2; // just for test
$invitation->invited_user_id = 3;
$invitation->remarks = '2';
$invitation->created_at = '2022-02-02';
$invitation->save();
}
}
Invitation Model
<?php
namespace TPam\SteveTribe\Model;
use Flarum\Database\AbstractModel;
class Invitations extends AbstractModel {
/**
* @var int|mixed
*/
public mixed $invitor_user_id;
/**
* @var mixed|string
*/
public mixed $invited_user_id;
/**
* @var mixed|string
*/
public mixed $remarks;
/**
* @var mixed|string
*/
public mixed $created_at;
/**
* {@inheritdoc}
*/
protected $table = 'st_invitations';
}
My Database(users
table)
migration
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Schema\Builder;
return [
'up' => function (Builder $schema) {
if ($schema->hasTable('st_invitations')) {
return;
}
$schema->create(
'st_invitations',
function (Blueprint $table) {
$table->integer("id");
$table->primary("id");
$table->integer('invitor_user_id')->unsigned();
$table->integer('invited_user_id')->unsigned();
$table->string('remarks', 64);
$table->timestamp('created_at')->useCurrent(); // set default value
$table->timestamp('updated_at')->useCurrent();
$table->foreign('invitor_user_id')
->references('id')
->on('users')
->onDelete('cascade');
$table->foreign('invited_user_id')
->references('id')
->on('users')
->onDelete('cascade');
$table->unique(["invitor_user_id", "invited_user_id"]);
}
);
},
'down' => function (Builder $schema) {
$schema->dropIfExists('st_invitations');
}
];