You can't use a one-to-many relationship for that, you need to use a many-to-many relationship with a pivot table category_post. Oh, and the foreign key should always be the same data type as the primary key that it references.
Oct 1, 2022
15
Level 4
Problem inserting multiple categories in posts table
It's not laravel, creating an oop blog project. I have categories and posts tables, categories table id is the foreign key of the posts table. I want to insert multiple selected categories' id in the posts table column ("category_id" type INT). how can I do that?
category_id column in the posts table:
category_id INT NOT NULL UNIQUE,
FOREIGN KEY (category_id) REFERENCES categories(id)
STORE METHOD:
// Store post
public function store()
{
$data['category_id'] = implode(',', Request::values()['category_id']);
dd($data);
// Insert post query
$query = sprintf(
"INSERT INTO %s (%s) VALUES(%s)",
"posts",
implode(', ', array_keys($data)),
":" . implode(', :', array_keys($data))
);
try {
$stm = pdo()->prepare($query);
$stm->execute($data);
} catch (PDOException $e) {
$this->jsonEncod(false, $e->getMessage());
}
}
IF I DO die & dump:
array(4) {
["title"]=>
string(20) "Culpa aut ullam nobi"
["slug"]=>
string(19) "dignissimos-quos-ut"
["body"]=>
string(21) "Distinctio Sit aut JJ"
["category_id"]=>
string(3) "1,2"
}
ERROR I GOT:
"SQLSTATE[01000]: Warning: 1265 Data truncated for column 'category_id' at row 1"
Thank you
Level 73
Please or to participate in this conversation.