![](/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.