【发布时间】: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