php - 如何解决 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;
});
解决方案
当您调用 eloquent 方法时,您的模型可能使用添加到查询子句的Post
Trait 。SoftDeletes
deleted_at is null
你有两个解决方案:
- 添加到您的迁移(创建新迁移),
$table->softDeletes();
其中添加了该列 - deleted_at。 SoftDeletes
从Post
模型中删除特征。
推荐阅读
- sharepoint - 当用户共享文档时,是否可以在页面或弹出窗口上显示警报消息
- python - 如何使用 python 或 C++ 获取数据集
- php - 图像未在 mysql 数据库中更新
- java - 调用 Lambda 函数时出现 ClassNotFoundException
- css - CSS:使元素的z-index低于兄弟的孩子
- python - python的算法列表
- c - C 编译指示“-Wunused-variable”在 Ubuntu 上不起作用
- javascript - 从 Javascript 中的 XML 数据中获取任何属性的值
- java - 使用 Swing 的测验布局
- python - 将预定时间戳传递给 celery beat / redbeat