0

I need to populate my database column from seeding. I have 'interested_in' column in user_profiles table and I need to populate it with according id from 'value_id' column from user_interests table. Both user_profiles and user_interests table are connected to users table ('user_id' column is in both tables). So if the value of 'value_id' column is for example 1 it needs to be 1 in 'interested_in' column, I need help on how to populate that 'interested_in' column from seeders. 'value_id' column is already populated. Here are my tables and example data and my code so far but it doesn't work currently, it shows 'Array to string conversion' error.

user_interests table

user_id    field_id    value_id
   1           1           1

user_profiles table

id    user_id    interested_in
 1       1           and here needs to be 1, to associate value_id (1) from user_interests table

UserProfileTableSeeder.php

class UserProfileTableSeeder extends Seeder
{
    use ChunkSeeder;

    public function run()
    {
        $users = User::all()->pluck('id');

        $user_interests = DB::table('user_interests')->select('value_id')->where('field_id', 1)->get();
        $user_interests_values = $user_interests->pluck('value_id')->toArray(); 

        $seed = [];

        foreach ($users as $userId) {
            $seed[] = factory(UserProfile::class)->make(
                [
                    'user_id' => $userId,
                    'interested_in' =>  $user_interests_values, // Shows array to string error!!!
                ]
            )->toArray();
        }

        $this->seedChunks($seed, [UserProfile::class, 'insert']);
    }
}

1 Answer 1

2

That's why $user_interests_values is an array as you can see in this line (at the end):

$user_interests_values = $user_interests->pluck('value_id')->toArray();

Try in the factory to change $user_interests_values to current($user_interests_values) or probably $user_interests_values['id'] or whatever.

PS: I am not really sure what's inside $user_interests_values, you can see it with a dd() and running the migration then (don't worry, the migration won't be successful because of the dd() and you will be able to run it later again until it finishes properly.

By the way, I recommend you to do something more legible than you did in your rum() method. I mean, something like this:

$interest = factory(UserInterests::class)->create();

factory(UserProfiles::class, 20)->create([
    'interest' => $interest->id,
]);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.