简体   繁体   中英

SQLSTATE[42S22]: Column not found: 1054 Laravel

I would like to get many "badges" to one "company" I have 3 tables companies, badgy, badgy_company as pivot table. What should I try/do? Can someone give me a hint or something?

company.blade.php

@foreach($listings->badgy as $type)
    <span class="label label-default">{!! $type->title !!}</span>
@endforeach 

Badgy.php

class Badgy extends Model{

protected $table = 'badgy';

public function badgy()
{
    return $this->hasMany(Company::class);        
}

If I remove protected $table = 'badgy'; I get error:

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'MYDATABASE.badgies' doesn't exist

Company.php

public function badgy()
{
    return $this->belongsToMany(Badgy::class);        
}

In page controllers I try:

$listings = Company::find($id);
$listings = Company::query()->get();

If I need to provide any more info, please, just ask.

You are not following the Laravel naming conventions. As a result, the default values used for relations by the framework don't work. You will have to set them manually as follows:

class Badgy
{
    protected $table = 'badgy'; // Laravel default would be 'badgies'

    public function companies()
    {
        return $this->belongsToMany(Company::class, 'badgy_company', 'category_id', 'company_id');
    }
}

class Company
{
    protected $table = 'companies'; // optional as the default is the same

    public function badgies()
    {
        return $this->belongsToMany(Badgy::class, 'badgy_company', 'company_id', 'category_id');
    }
}

Please also have a look at another answer of mine where I explain some important pieces regarding relationships and naming conventions. Because in a perfect scenario you would have the following tables and columns:

companies:
  - id
  - name

badgies:
  - id
  - title

badgy_company:
  - id
  - badgy_id
  - company_id

Which would allow your models to look like this:

class Badgy
{
    public function companies()
    {
        return $this->belongsToMany(Company::class);
    }
}

class Company
{
    public function badgies()
    {
        return $this->belongsToMany(Badgy::class);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM