关系在Laravel 5 [英] Relations in Laravel 5

查看:66
本文介绍了关系在Laravel 5的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的产品型号:

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

我的模特Categoria具有:

and my model Categoria has:

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

尝试在视图view中从产品访问:

try to access from produto in the view view:

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

返回数组:

{"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"}

这不应该返回Categoria的对象吗? 我想这样访问:

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

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

不是:

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

但这是一个数组:

Trying to get property of non-object

但是在文档中,返回的是对象而不是数组 Laravel .有什么想法吗?

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

推荐答案

您可能需要在关系中指定本地和外键. 检查一下:

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

如果您不使用常规ID名称,则应指定它.在这种情况下

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

这篇关于关系在Laravel 5的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆