如何使用外键约束 laravel 播种 table

How to seed a table with a foreign key constraint laravel

如何使用 comments.post_id 作为 post.id.

的外键来播种我的评论 table

我有一个用于评论的工厂 table 但没有用于 Post table.The Post table 我手动填充所以我不能 link工厂。

由于 FK 限制,我在添加评论时遇到问题。我手动插入一个 post.id,但不知道如何让 Laravel 自动选择一个 ID。

提前致谢,山姆

评论工厂

<?php

namespace Database\Factories;

use App\Models\Comment;
use App\Models\Post;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;


class CommentFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = Comment::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            //
            'post_id'=> 38,
            'author' => $this->faker->name(),
            'comment' => $this->faker->realText(150),
            'approved' => 0,
        ];
    }
}

评论播客

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;

use App\Models\Comment;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;

class CommentSeeder extends Seeder
{
    /**
     * Run the database seeds.
     *
     * @return void
     */
    public function run()
    {
        // factory(App\Comment::class, 25)->create();
        Comment::factory()->count(rand(1,5))->create(); 
    }
}

**评论模型

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;


class Comment extends Model
{
    use HasFactory;

    protected $fillable = ['author','comment', 'post_id','approved'];

    public function post()
    {
        return $this->belongsTo(Post::class);
    }

    
}

**

我使用 pluck() 创建了一个包含所有 post.id

的数组
$posts = Post::all()->pluck('id')->toArray();

并使用 randomElement() 来选择一个随机 id 作为 post_id

$post_id = $this->faker->randomElement($posts);

非常感谢您的建议!

Post::all()->random()->id, 始终获取任何随机 post ID 并为其分配评论。

<?php

namespace Database\Factories;

use App\Models\Comment;
use App\Models\Post;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;


class CommentFactory extends Factory
{
    /**
     * The name of the factory's corresponding model.
     *
     * @var string
     */
    protected $model = Comment::class;

    /**
     * Define the model's default state.
     *
     * @return array
     */
    public function definition()
    {
        return [
            //
            'post_id'=> Post::all()->random()->id, <---- try this.
            'author' => $this->faker->name(),
            'comment' => $this->faker->realText(150),
            'approved' => 0,
        ];
    }
}