如果大家对匿名函数那里不理解,也可以用我下面的非匿名函数的写法填充数据。

如果大家对匿名函数那里不理解
也可以用我下面的非匿名函数的写法填充数据。

<?php

use Illuminate\Database\Seeder;
use App\Models\Topic;
use App\Models\User;
use App\Models\Category;

class TopicsTableSeeder extends Seeder
{
    public function run()
    {
        //获得用户id和分类id
        $user_ids = User::all()->pluck('id')->toArray();
        $catetory_ids = Category::all()->pluck('id')->toArray();
        //实例化faker
        $faker = app(Faker\Generator::class);

        $topics = factory(Topic::class)
            ->times(100)
            ->make();
        //循环赋值 不需要只用use
        foreach($topics as $topic){
            $this->setValues($topic,$user_ids,$catetory_ids,$faker);
        };

        //如果使用匿名函数 需要使用use 关键字 引入变量
//        $topics = factory(Topic::class)
//            ->times(100)
//            ->make()
//            ->each(function ($topic,$index)
//                //注意 use写在大括号的外面
//                use ($user_ids,$catetory_ids,$faker)
//            {
//                $topic->user_id = $faker->randomElement($user_ids);
//                $topic->category_id = $faker->randomElement($catetory_ids);
//            });

        //添加数据入库
        Topic::insert($topics->toArray());
    }

    //如果不用匿名函数 这么写
    function setValues($topic,$user_ids,$catetory_ids,$faker)
    {
        $topic->user_id = $faker->randomElement($user_ids);
        $topic->category_id = $faker->randomElement($catetory_ids);
    }
}

《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
《G01 Go 实战入门》
从零开始带你一步步开发一个 Go 博客项目,让你在最短的时间内学会使用 Go 进行编码。项目结构很大程度上参考了 Laravel。
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!