Relationship error and method not found

Asked

Viewed 79 times

0

I am studying Laravel and I have difficulties to realize the relationship of an associative table that connects 3 tables of domain. example of my model:

inserir a descrição da imagem aqui

The problem is that I can’t map from my command to other entities. Just follow my code:

Model da Comanda:

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


}

Model of the Waiter:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

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

Bureau model:

<?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 in 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 method table, nor if this mapping I did is correct. You could help me with that ?

1 answer

0


In your Command model you must indicate your field id in the second relationship parameter 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()

  • 1

    Solved. Thank you very much !

  • I thank you. In this case I ask you to mark my answer as valid

Browser other questions tagged

You are not signed in. Login or sign up in order to post.