Search code examples
phplaravelhas-manybelongs-to

Column not found: 1054 Unknown column in 'field list'


I don't know why I keep seeing the below error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'ec_svdiscount_services.sv_discount_id' in 'field list'

I have edited my database and cleared all cache by doing:

php artisan cache:clear
php artisan config:clear
php artisan route:clear
php artisan view:clear
php artisan clear-compiled
composer dumpautoload

all in an attempt to erase every record of sv_discount_id, which is no longer in use anywhere on my project. I am rather supposed to have svdiscount_id which I have created in the controller, models, repository, and all relevant. Please what am I doing wrong? How can I stop sv_discount_id from showing up.


Solution

  • When your model name is SvDiscount::class when used in a relation, laravel will deduce the foreign key from the class name.

    For example:

    Class product 
    {
        public function discount()
        {
            return $this->belongsTo(SvDiscount::class);
        }
    }
    

    When using this relation in a code, laravel will deduce that the foreign key present in products table is named sv_discount_id.

    One simple solution would be to rename those fields to sv_discount_id.

    Another solution would be to specify the foreign key in the relation (documentation):

    Class product 
    {
        public function discount()
        {
            return $this->belongsTo(SvDiscount::class, 'svdiscount_id');
        }
    }