SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.post_id' in 'where clause

Updated at 08-Sep-2021, By samar

Error SQLSTATE[42S22]: Column not found: 1054 Unknown column 'users.post_id' in 'where clause found in laravel because you did not define the right relationship method in model.

  • Get user/author detail using belongsTo relation on post model

    //app\Models\Post.php
    class Post extends Model
    {
    
        //Add user method in existing post model
        public function user(){
            return $this->belongsTo('App\Models\User');
        }
    }
    
    //Code snippet to get the user/author details with post.
    $data = Post::with('user')->first();
    dd($data);
    
    //Import post model after the namespace in controller or anywhere you want to use the above code
    use App\Models\Post;
    

    You have to create a user method with belongsTo relationship in the post model. It helps you to get the user or author information using the user_id (foreign_id) of the posts table and id (primary key) column of users table.

Back to code snippet queries related laravel