Relations in Laravel 5

2019-08-13 18:30发布

问题:

My Product model:

public function categoria(){
    return $this->belongsTo('estoque\Categoria');
}

and my model Categoria has:

public function produtos(){
        return $this->hasMany('estoque\Produto');
}

try to access from produto in the view view:

<td> {{$p->categoria}} <td>

Return an array:

{"id":1,"nome":"Cerveja","descricao":"Todas cervejas","ativo":1,"created_at":"2015-10-24 13:53:14","updated_at":"2015-10-24 13:53:14"}

This should not return an object of Categoria? I would like to access like this:

<td> {{$p->categoria->nome}} <td>

not :

{{$p->categoria['nome']}}

But it is an array:

Trying to get property of non-object

But in the documentation the return is an object not arrayLaravel. Any ideas?

回答1:

You probably need to specify the local and foreign key in your relation. Check this:

http://laravel.com/docs/5.1/eloquent-relationships

You are forgetting write something like this:

return $this->hasMany('estoque\Produto', 'foreign_key', 'local_key');

If you are not using convenctional ID names, you should specify it. In this case

return $this->hasMany('estoque\Produto', 'categoria_id', 'id');
return $this->belongsTo('estoque\Categoria', 'id', 'categoria_id');


标签: php laravel-5