L
L
LEIFEI2021-11-17 05:13:02
Laravel
LEIFEI, 2021-11-17 05:13:02

How to add multiple values ​​to foreign in Laravel Factory?

Hello everyone, I can't figure out how to add multiple foreign relations to the factory and the seeder.

Have a factory

$category_id = [ '1', '2', '3', ];
 return [ 'category_id' => $category_id, ]

It turns out that in the category field I am trying to enter an array of id categories, in migration I try to do this:
$table->bigInteger('category_id')->unsigned(); 
            $table->foreign('category_id')
                  ->references('id')
                  ->on('categories');


I run the migration, but it gives an error. What am I doing wrong?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2021-11-17
@LEIFEI

The column name category_idtranslates as "category identifier" (singular). The type of this column is number. Why did you decide that you can write an array (and for some reason strings) there?
You write "I'm running the migration, but it gives an error". Factories are not related to migrations, so the error is in something else that is not mentioned in the question. What exactly is written in the error? Or maybe you "run migrations" with a flag --seedand it's still in the factory? We can only guess.
If you want to be able to bind several categories to your entity, then the table structure should be different .

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question