首页 > 解决方案 > 如何解决 SQLSTATE [42S22]: Column not found: 1054 Unknown column 'id' in 'where 子句'

问题描述

我正在处理一对一的数据库 Eloquent 关系,但是在编写代码之后,我收到了一个错误:

SQLSTATE [42S22]:未找到列:1054 'where 子句'中的未知列'posts.deleted_at'(SQL select * from `posts` where `posts`.`user_id` = 1 and `posts`.`user_id` is not null and `posts`.`deleted_at` is null limit 1:)

此代码用于我链接 user_id 的 post 表

表迁移后

class CreatePostTable extends Migration
{
   
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('user_id')->unsigned();
            $table->string('title');
            $table->text('body');
            $table->timestamps();
        });
    }

  
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

这是我必须链接帖子的用户表

用户模型迁移

class CreateUsersTable extends Migration
{
    
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }


    public function down()
    {
        Schema::dropIfExists('users');
    }
}

用户.php代码


 
public function post(){
   return $this->hasOne('App\Post'); //select * from post where user_id = 1
    
}

这是路线:

路线\web.php

 Route::get('user/{id}/post', function ($id) {
     

    return User::find($id)->post;
 });

标签: phpmysqleloquentlaravel-7

解决方案


当您调用 eloquent 方法时,您的模型可能使用添加到查询子句的PostTrait 。SoftDeletesdeleted_at is null

你有两个解决方案:

  1. 添加到您的迁移(创建新迁移),$table->softDeletes();其中添加了该列 - deleted_at。
  2. SoftDeletesPost模型中删除特征。

推荐阅读