SQLSTATE [42S22]:找不到列:1054 Laravel

时间:2018-08-03 14:33:34

标签: php laravel laravel-5 eloquent many-to-many

我想给一个“公司”拿很多“徽章” 我有3个表格公司,badgy,badgy_company作为数据透视表。 我应该尝试/做什么?有人可以给我提示吗?

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);        
}

如果我删除protected $table = 'badgy';,则会收到错误消息:

  

SQLSTATE [42S02]:找不到基表或视图:1146表'MYDATABASE.badgies'不存在

Company.php

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

在页面控制器中,我尝试:

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

如果我需要提供更多信息,请询问。

1 个答案:

答案 0 :(得分:1)

您未遵循Laravel的命名约定。结果,框架用于关系的默认值不起作用。您必须手动设置它们,如下所示:

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');
    }
}

也请看看another answer of mine,在这里我将解释一些有关关系和命名约定的重要内容。因为在理想情况下,您将具有以下表格和列:

companies:
  - id
  - name

badgies:
  - id
  - title

badgy_company:
  - id
  - badgy_id
  - company_id

这将允许您的模型如下所示:

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

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