Relationship error and method not found

0

I am studying Laravel and I have difficulties to perform the relationship of an associative table linking 3 domain tables. example of my template:

The problem is that I can not map from my command to other entities. Here is my code:

Command Model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Comanda extends Model
{

    public function mesas(){
        return $this->belongsToMany('App\Mesa');
    }
    public function garcom(){
        return $this->hasOne('App\Garcom');
    }


}

Waiter's model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Garcom extends Model
{
    protected $fillable = ['nome', 'setor'];
}

Table Template:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Mesa extends Model
{
    protected $fillable = ['setor'];

    public function garcoms(){
        return $this->belongsToMany('App\Garcom')->withtimestamps();
    }
    public function produtos(){
        return $this->belongsToMany('App\Produto')->withtimestamps();
    }
}

Product Model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Produto extends Model
{
    protected $fillable = ['nome', 'valor'];
}

To test all this, I used the artisan tinker and typed the following:

$comanda = App\Comanda::first()
$comanda->mesas()

But I had the following error as a return:

  BadMethodCallException with message 'Call to undefined method Illuminate\Database\Query\Builder::mesas()'

At this point I do not know why the object commands does not find the table method, so little if this mapping I made is correct. Could you help me with that?

    
asked by anonymous 18.07.2018 / 16:07

1 answer

0

In your Command model you must enter the id of your field in the second parameter of the relationship as below:

public function mesas(){
   return $this->belongsToMany('App\Mesa', 'mesa_id');
}

This should work

-

Edit 2: The undefinied method error I would try without the parentheses '()' on tables ()

    
18.07.2018 / 16:30