【问题标题】:how to solve SQLSTATE[42S22]: Column not found: 1054 Unknown column 'id' in 'where clause'如何解决 SQLSTATE [42S22]: Column not found: 1054 Unknown column 'id' in 'where 子句'
【发布时间】:2020-07-08 20:21:47
【问题描述】:

我正在处理一对一的数据库 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');
    }
}

User.php 代码


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

这是路线:

Routes\web.php

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

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

【问题讨论】:

  • 直接检查表的结构(通过 CLI 或原始 SQL)以获取正确的列名。 PS。 where `posts`.`user_id` = 1 and `posts`.`user_id` is not null - 如果第一个条件为真,那么第二个条件也为真 - 所以第二个条件是多余的。
  • 用户表的主键是什么?
  • 用户表的主键是'id=1'
  • 谢谢你我试过了,它解决了我的问题@SenthilnadhanRamasamy

标签: php mysql eloquent laravel-7


【解决方案1】:

您尚未在 posts 表中创建 deleted_at 列。如果您在posts 表中创建deleted_at 列,那么它将起作用。

【讨论】:

  • 这个答案令人费解。请尝试发布正确的答案。
【解决方案2】:

您的 Post 模型可能使用 Trait SoftDeletes 在您调用 eloquent 方法时添加到查询子句 deleted_at is null

你有两个解决方案:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-01
    • 2019-06-06
    • 1970-01-01
    • 2020-10-13
    • 2018-02-04
    • 2016-07-22
    相关资源
    最近更新 更多