【问题标题】:Trying to Create Fake Posts on Laravel but meeting with QueryException with message 'SQLSTATE[23000]尝试在 Laravel 上创建虚假帖子,但遇到带有消息“SQLSTATE [23000]”的 QueryException
【发布时间】: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))'

标签: php mysql laravel


【解决方案1】:

无法添加或更新子行:外键约束失败本质上意味着,您正在尝试向您的帖子表添加一行,而用户表中没有匹配的行 (user_id)。

【讨论】:

  • 我检查了我的数据库,我可以看到我有一个'user_id',我也尝试了代码@nemesiscb,但我得到了上面的错误代码......
  • 查看迁移文件后,您应该再次尝试迁移。这个问题可能出在数据库结构上。
【解决方案2】:

尝试用这个来改变模型 Post 中的关系函数:

public function user()
{
    return $this->belongsTo(User::class , 'user_id', 'id');
}

如果不进行此更改,您将尝试将 Post.id(而不是 user_id)与 User.id '连接',而 Post.id 似乎不存在,至少我从日志中看到的那样。

【讨论】:

  • 我仍然在 Illuminate\Database\QueryException 下面收到错误代码,并带有消息“SQLSTATE[23000]:完整性约束违规:1452 无法添加或更新子行:外键约束失败 (posty .posts, CONSTRAINT posts_user_id_foreign FOREIGN KEY (user_id) REFERENCES users (id) ON DELETE CASCADE) (SQL: insert into posts (body, @9876543130@, @876543130@, @833) created_at) 值 (Velit deserunt libero voluptatem iste nam laudantium sit Molestiae non itaque voluptatem voluptatem., 2, 2021-04-13 13:52:28, 2021-04-13 13:52:28))'
  • 我认为迁移/数据库结构和相关模型存在一些问题,正如@ali-ali 所说:1.在用户的插入中提到'用户名'没有默认值,但是在 laravel 中插入你只有 'name; 2.用户中有id吗?自动递增?如果您发布迁移和/或数据库结构,我们可以在不猜测的情况下对其进行审查。 (如果不需要,也可以尝试删除约束)
  • 表格是 laravel 自动生成的,所以没想到会有问题...不过如果你能多指教我会很高兴的。
  • 编辑帖子至少添加您的迁移文件,Laravel 默认不添加 costraint,那里有问题
【解决方案3】:
  1. 当我尝试使用 tkinter 创建虚假帖子时,user_id 出现错误,因为我分配给了不同的 user_id。

  2. 正如@AliAli 所说,我必须从可为空的用户名中删除。

【讨论】:

    猜你喜欢
    • 2019-05-21
    • 1970-01-01
    • 2020-09-30
    • 1970-01-01
    • 1970-01-01
    • 2013-12-24
    • 2021-02-03
    • 2018-02-15
    • 1970-01-01
    相关资源
    最近更新 更多