【发布时间】:2021-07-08 07:32:58
【问题描述】:
尝试使用 tinker 创建虚假帖子,但遇到以下错误代码
Illuminate\Database\QueryException with message 'SQLSTATE[23000]: Integrity constraint violation: 1452 cannot add or update a child row: a foreign key constraint failed (posty.posts, CONSTRAINT posts_user_id_foreign FOREIGN KEY ( user_id) 参考 users (id) ON DELETE CASCADE) (SQL: insert into posts (body, user_id, updated_at, created_at) 值 (Velit deserunt tempore 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))'
下面是我的代码
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);
}
}
【问题讨论】:
-
可能重复see here
-
您能否回答这些问题,以便我们帮助您获得正确答案?您正在运行什么命令来创建帖子?你的播种机课程的内容是什么?你想完成什么场景?
-
1.我正在使用 tinker 在 laravel 上创建虚假帖子。 2. App\Models\Post::factory->times(200)->(['user_id' =>2]); 3. public function user() { return $this->belongsTo(User::class, 'user_id', 'id');注意:我也在我的 Post.php 中使用了这个受保护的 $fillable= [ 'body', 'user_id', ];
-
@Emmanuel 这意味着您的用户表中没有 ID 为“2”的用户。要么在你的表上创建一个 id 为“2”的用户,要么你可以通过使用添加一个有 200 个帖子的新用户... User::factory() ->times(1) ->has(Post::factory( )->count(200))->create();
-
这是我得到的错误... Illuminate\Database\QueryException with message 'SQLSTATE[HY000]: General error: 1364 Field 'username' doesn't have a default value (SQL: insert into
users(name,email,email_verified_at,password,remember_token,updated_at,created_at) 值 (Brett Lebsack, lavonne39@example.org, 2021-04-1 31:31, $2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi, QJXf2hSkqX, 2021-04-14 01:31:31, 2021-04-14 01:31:31))'