Doubt with relationship One to Many

Asked

Viewed 355 times

5

I have two tables, produtos and categorias.
In my view of produtos i want to show the category name of that product, not its code.

Model de Categoria Category.php

namespace MagicCommerce\Site\Cadastros;

class Categoria extends \Eloquent {
    public function produtos() {
        return $this->hasMany('Produto');
    }
}

Product Model Product.php

namespace MagicCommerce\Site\Cadastros;

class Produto extends \Eloquent {
    public function categoria() {
        return $this->belongsTo('Categoria');
    } 
}

And in my view i try to call the relationship using:

@foreach ($produtos as $p)
{{ $p->categoria->nome }}
@endforeach

And I am returned the following:

Symfony Component Debug Exception Fatalerrorexception Class 'Category' not found

Access the database data usually, only the relationship does not work. dump-autoload, but without success.

1 answer

3

Your problem is in solving the class name, add to your controller:

use MagicCommerce\Site\Cadastros\Categoria;

use MagicCommerce\Site\Cadastros\Produto;
  • 1

    Actually, you have to add this to your controller.

  • Exactly Elena, because the models are in the same namespace, so there’s no need to put a use on them.

  • well remembered! response edited

Browser other questions tagged

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