![](/img/trans.png)
[英]QueryException in Connection.php line 729: SQLSTATE[23000]: Laravel 5.2
[英]Trying to Create Fake Posts on Laravel but meeting with QueryException with message 'SQLSTATE[23000]
尝试使用 tinker 创建假帖子,但遇到以下错误代码
Illuminate\Database\QueryException 与消息'SQLSTATE [23000]:完整性约束违规:1452 无法添加或更新子行:外键约束失败( posty
posts
CONSTRAINT posts_user_id_foreign
FOREIGN KEY ( user_id
) REFERENCES users
( id
) ON DELETE CASCADE)(SQL:插入posts
( body
、 user_id
、 updated_at
、 created_at
)值(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))'
以下是我的代码
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);
}
}
无法添加或更新子行:外键约束失败本质上意味着,您正在尝试向您的帖子表中添加一行,而用户表中没有匹配的行 (user_id)。
尝试更改 model 中的关系 function 发布:
public function user()
{
return $this->belongsTo(User::class , 'user_id', 'id');
}
如果没有此更改,您将尝试将 Post.id(而不是 user_id)与 User.id '连接',而 Post.id 似乎不存在,至少我从日志中看到的那样。
当我尝试使用 tkinter 创建虚假帖子时,user_id 出现错误,因为我分配给了不同的 user_id。
正如@AliAli 所说,我必须从可为空的用户名中删除。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.