How can I seed my Comments table with comments.post_id as Foreign Key to post.id.
I have a Factory for the Comments table but not for the Post table.The Post table I populate manually so I can not link Factories.
I have a problem with adding a comment, because of the FK constraint. I insert a post.id manually, but don;t know how to let Laravel choose an id automatically.
Thanks in advance, Sam
CommentFactory
<?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();
}
}
**Comment Model
<?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);
}
}
**