douying3251 2017-10-26 19:11
浏览 60
已采纳

如何使用带有两个循环的修补程序为数据库虚拟数据播种 - Laravel PHP

I try to seed my mysql database with tinker commands and are struggeling combining two each loops...

I have a table movies, users, and ratings. I want to seed the database with 10 movies, 3 users, and for each user a rating for each movie.

I am putting data into the two tables users und movies and saving those to $movies and $users. And try to create 3 ratings with the user_id and the movie_id for each movie with the following lines.

$users = factory('App\User',3)->create();
$movies= factory('App\Movie',10)->create();
$movies->each(function($movie){ $users->each(function($user){ factory('App\Rating',3)->create(['movie_id'=>$movie->id,'user_id'=>$user->id]);}); });

echoing out $movies and $users show me the data are in there. The last line gives me back an error: HP Notice: Undefined variable: users on line 2

tried to simplify the syntax for testing:

$movies->each(function ($movie) {$users->each(function($user) {echo $movie;});});

with the same error.

I guess it is that the $users variable isn't defined inside the first function? Do I have to define $users inside the first function? How do i do that if i dont want to create 3 new users for each movie? Maybe i can use a for loop somehow to iterate through the users and retrieve the users ids that way?

thanks in advance for helping me

  • 写回答

1条回答 默认 最新

  • dongquming3255 2017-10-26 19:14
    关注

    Be sure to use ($users) as well. You need declare the variables used out of the function scope when using Closures in PHP!

    $movies->each(function($movie) use ($users){ 
        $users->each(function($user) use ($movie){ 
            factory('App\Rating',3)
         ->create(['movie_id'=>$movie->id,'user_id'=>$user->id]);
        }); 
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?