如何种子自引用表Laravel 5.1

时间:2015-06-26 19:28:04

标签: php laravel-5 laravel-seeding

如何使用同一个表中的两个外键对表进行种子处理,如消息:

迁移:

    public function up()
    {
        Schema::create('messages', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('to')->unsigned();
            $table->integer('from')->unsigned();
            $table->integer('parent_id')->unsigned()->nullable();
            $table->text('body');
            $table->boolean('status')->default(false);
            $table->timestamps();
        });

        Schema::table('messages', function (Blueprint $table) {
            $table->foreign('to')
                    ->references('id')->on('users')
                    ->onDelete('cascade');

            $table->foreign('from')
                    ->references('id')->on('users')
                    ->onDelete('cascade');

            $table->foreign('parent_id')
                    ->references('id')->on('messages');

        });
    }

ModelFactory:

$factory->define(App\Message::class, function($faker) {

    return [
        'body' => $faker->text
        'from' => //user id,
        'to' => //user id,
        'parent_id' => //message id
    ];

});
  1. 我如何在这里获得用户ID?
  2. 如何获取ID的现有消息行?

2 个答案:

答案 0 :(得分:2)

$messages = factory(App\Message::class, 20)->create();
$messageIds = DB::table('messages')->lists('id'); // returns array of userids
DB::table('categories')->where('id', $rowid); // where $rowid is the id which you want

完全解决方案就像这样

class MessagesTableSeeder extends Seeder
{
    public function run()
    {
        // start with some cleanup    
        DB::table('messages')->truncate();
        // Create some App\Message instances...
        $messageCount = 30;
        $messages = factory(App\Message::class, $messageCount)->create();
        $messageIds = DB::table('messages')->lists('id');
        for($i=0; $i<$messageCount - 1; $i++) {
            $randomizedMessageIds = $messageIds;
            shuffle($randomizedMessageIds);
            DB::table('messages')->where('id', $i)->update(['parent_id'=>$randomizedMessageIds[$i]]);
        }
    }
}

答案 1 :(得分:0)

晚会,但我有另一个解决方案:

为任何模型创建工厂时,前几次,让parent_id为0.在DB中指定的创建条目之后,您可以传入已创建的实际获取数据。

我正在使用它来自我引用类别和子类别。

 $factory->define(CMS\Models\Category::class, function (Faker\Generator $faker) {
    $users = \CMS\Models\User::all()->pluck('user_id')->toArray();

    /* Get all categories, if there are less then 4, the reference 
    is an array with a 0, meaning no parent. After 4 are created, we 
    start picking random categories s a parent ID, the list will grow 
    so does the variation. Of course you can set the minimum amount 
    of created categories as you wish.*/

    $categories = \CMS\Models\Category::all()->pluck('category_id');
    if (count($categories) <= 4) {
        $categories = [0];
    } else {
        $categories = $categories->toArray();
    }
    return [
        'category_id' => $faker->unique()->numberBetween(1,1000),
        'title' => $faker->sentence(1,40),
        'description' => $faker->text(50),
        'content' => $faker->paragraph(rand(3,5)),
        'approved' => $faker->boolean(),
        'trashed' => $faker->boolean(),
        'type' => $faker->randomElement('post','product'),
        'user_id' => $faker->randomElement($users),
        'parent_id' => $faker->randomElement($categories),
        'created_at' => $faker->dateTimeThisYear,
        'updated_at' => $faker->dateTimeThisYear,
    ];
});

如果设置将parent_id添加到数据库所需的count($categories) <= 1,则使用此方法将至少有一个没有父项的条目。如果绝对需要让所有条目都有parent_id,则只需手动更改数据库中的1列。