I'm working on database Eloquent Relationship One to one but after writing code, I'm getting an error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'posts.deleted_at' in 'where clause' (SQL:
select * from `posts` where `posts`.`user_id` = 1 and `posts`.`user_id` is not null and `posts`.`deleted_at` is null limit 1
)
this code is for post table where I linked the user_id
Post table migration
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');
}
}
this is the user table where I have to link the post
User model migration
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 code
public function post(){
return $this->hasOne('App\Post'); //select * from post where user_id = 1
}
and this is the route:
Routes\web.php
Route::get('user/{id}/post', function ($id) {
return User::find($id)->post;
});
where `posts`.`user_id` = 1 and `posts`.`user_id` is not null
- if 1st condition is true then 2nd is true too - so 2nd condition is excess. – Akina