【发布时间】:2021-08-22 01:40:49
【问题描述】:
如何使用 cmets.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,
];
}
}
CommentSeeder
<?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);
}
}
**
【问题讨论】:
-
在
CommentFactory->definition,如何从数据库中获取帖子ID列表并随机选择一个返回? -
阅读这篇文章:medium.com/@gdiasdasilva/…
-
非常感谢,它的工作!我使用 pluck() 方法创建数组,使用 randdomElement() 方法选择随机 id。
标签: php laravel eloquent faker