Trying to create Fake Posts by using tinker but met with the error code bellow
Illuminate\Database\QueryException with message 'SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails ( posty
. posts
, CONSTRAINT posts_user_id_foreign
FOREIGN KEY ( user_id
) REFERENCES users
( id
) ON DELETE CASCADE) (SQL: insert into posts
( body
, user_id
, updated_at
, created_at
) values (Velit deserunt tempore vitae et et aliquid explicabo autem occaecati dolores veritatis accusamus cum natus sint eius laudantium mollitia maxime dolorem eius enim., 2, 2021-04-13 08:42:17, 2021-04-13 08:42:17))'
Below are my codes
PostFactory.php
<?php
namespace Database\Factories;
use App\Models\Post;
use Illuminate\Database\Eloquent\Factories\Factory;
class PostFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = Post::class;
/**
* Define the model's default state.
*
* @return array
*/
public function definition()
{
return [
'body' => $this->faker->sentence(20),
];
}
}
PostController.php
<?php
namespace App\Http\Controllers;
use App\Models\Post;
use Illuminate\Http\Request;
class PostController extends Controller
{
public function index(){
// $posts= Post::get(); //Collect all...
$posts= Post::paginate(20); //How many you want per page...
return view('posts.index', [
'posts' => $posts
]);
}
public function store(Request $request)
{
//dd('ok');
$this->validate($request, [
'body' => 'required',
]);
Post::create([
'user_id' => auth()->id(),
'body' => $request->body,
]);
return back();
}
}
Post.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
use HasFactory;
protected $fillable= [
'body',
'user_id',
];
/**
* Get the user that owns the Post
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function user()
{
return $this->belongsTo(User::class);
}
}
Cannot add or update a child row: a foreign key constraint fails essentially means that, you are trying to add a row to your posts table for which no matching row (user_id) is present in user table.
Try to change relationship function in model Post with this:
public function user()
{
return $this->belongsTo(User::class , 'user_id', 'id');
}
Without this change you are trying to 'connect' Post.id (instead of user_id) with User.id, and Post.id doesn't seem to exist, at least by wath I see from the log.
The user_id had errors while I was trying to create the fake posts using tkinter because I was assigning to a different user_id.
As @AliAli has said, I had to remove the username from nullable.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.