0
votes

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.

1
php artisan migrate, your table badgies not exist - J. Doe
Is your table badges or badgy? - Devon
My table in phpmyadmin is badgy. - Roga Men
Edited. I have tables; companies, badgy, badgy_company as pivot table. - Roga Men
If your variable $listings is meant to contain your companies, and you want for each companies to display its "badgy", so you miss the definition of the Company class in your post. Please provide it and we can help you more. - Anwar

1 Answers

1
votes

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