Laravel - SQLSTATE[42S22]: Column not found: 1054 Unknown column

14,865

In order to specify the foreign keys, you need to do so in the model when you define the relationships.

From the docs for a belongsTo relationship:

In the example above, Eloquent will try to match the user_id from the Phone model to an id on the User model. Eloquent determines the default foreign key name by examining the name of the relationship method and suffixing the method name with _id. However, if the foreign key on the Phone model is not user_id, you may pass a custom key name as the second argument to the belongsTo method

In other words, in your Post model where you define the relationship with the User, you need to add a second argument that specifies the foreign key name:

public function user()  {
  return $this->belongsTo('NacionGrita\User', 'id_user');
}

From the docs for a hasOne and hasMany relationship:

Eloquent assumes the foreign key of the relationship based on the model name. In this case, the Phone model is automatically assumed to have a user_id foreign key. If you wish to override this convention, you may pass a second argument to the hasOne method:

In other words, in your User model where you define the relationship with the Post, you need to once again add a second argument that specifies the foreign key name:

public function posts() {
  return $this->hasMany('NacionGrita\Post', 'id_user');
}

Link to docs: https://laravel.com/docs/5.1/eloquent-relationships

Share:
14,865
CanKer
Author by

CanKer

Software developer since 2014, working with the most famous JS libraries and frameworks. Experienced with relational and non relational databases; the most used architectures as MVC, Micro-services, Serverless, Event- Driven, and Design Patterns. I’m ease to learn and adapt. Proactive and functional in all my work and way to live. I’m more logical than creative but trying to find a balance. Always trying to defeat all my weaknesses.

Updated on June 14, 2022

Comments

  • CanKer
    CanKer almost 2 years

    Hello im getting this error Illuminate\Database\QueryException with message 'SQLSTATE[42S22]: Column not found: 1054 Unknown column 'posts.user_id' in 'where clause' (SQL: select * frompostswhereposts.user_id= 1 andposts.user_idis not null)' and I don't know why if in my database I don't have user_id, I have id_user...

    This is my migration table

    <?php
    
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Database\Migrations\Migration;
    
    class CreateUsersTable extends Migration
    {
    
        public function up()
        {
            Schema::create('users', function (Blueprint $table) {
                $table->increments('id');
                $table->string('user')->unique();
                $table->string('email')->unique();
                $table->string('password', 60);
                $table->string('img');
    
                $table->rememberToken();
                $table->timestamps();
            });
        }
    
        public function down()
        {
            Schema::drop('users');
        }
    }
    

    This other is my posts migration archive

    <?php
    
    use Illuminate\Database\Schema\Blueprint;
    use Illuminate\Database\Migrations\Migration;
    
    class AddPosts extends Migration
    {
        /**
         * Run the migrations.
         *
         * @return void
         */
        public function up()
        {
            Schema::create('posts', function (Blueprint $table) {
                $table->increments('id');
                $table->string('nombre');
                $table->longText('contenido');
    
                $table->unsignedInteger('id_user');
    
                $table->timestamps();
            });
    
            Schema::table('posts', function($table) {
              $table->foreign('id_user')->references('id')->on('users');
            });
        }
    
        /**
         * Reverse the migrations.
         *
         * @return void
         */
        public function down()
        {
            Schema::drop('posts');
        }
    }
    

    this is my Post model

    <?php
    
    namespace NacionGrita;
    
    use Illuminate\Database\Eloquent\Model;
    
    class Post extends Model
    {
        protected $table = "posts";
        protected $fillable = ['nombre', 'contenido', 'id_user'];
    
        public function imagenes()  {
          return $this->belongsToMany('NacionGrita\Imagen');
        }
        public function categorias()  {
          return $this->belongsToMany('NacionGrita\Categoria');
        }
        public function tags() {
          return $this->belongsToMany('NacionGrita\Tag');
        }
        public function user()  {
          return $this->belongsTo('NacionGrita\User');
        }
    
    }
    

    and this is my users Model

    <?php
    
    namespace NacionGrita;
    
    use Illuminate\Foundation\Auth\User as Authenticatable;
    
    
    class User extends Model
    {
    
        protected $table = "users";
        protected $fillable = [
            'user', 'email', 'password', 'img'
        ];
    
        public function posts() {
          return $this->hasMany('NacionGrita\Post');
        }
    
        protected $hidden = [
            'password', 'remember_token',
        ];
    }
    

    If I change my "posts" table column from id_user to user_id it works but I don't know why I have to change the column name if its supposed to works because I specified the foreigns keys or Im doing something wrong?

    Thanks for help