问题描述
如何使用comments.post_id 作为post.id 的外键为我的Comments 表设置种子。
我有一个用于 Comments 表的工厂,但没有用于 Post 表。我手动填充 Post 表,因此我无法链接工厂。
由于 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,
始终获取任何随机帖子 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,];
}
}