Laravel中的1:1关系返回Undefined属性

时间:2015-11-24 20:40:35

标签: laravel laravel-5 eloquent

在处理1:1数据库关系时,我一直在Laravel 5中收到此错误:

Undefined property: Illuminate\Database\Eloquent\Collection::$owner

在我的控制器中我有方法“东西”。当我返回$ stuff时,我得到:

[{"id":4,"demoId":2,"slug":"loremipsum","languageId":1,"countryId":1,"created_at":"-0001-11-30 00:00:00","updated_at":"-0001-11-30 00:00:00"}]

关系在“demoId”上。

在我的模特中我有这个:

public function owner(){
    return $this->belongsTo('App\Demotable2');
}

我正在使用此代码,这会产生错误:

$routine = $stuff->owner->get()->toArray();

我希望在demotable2中获取信息。我做错了什么?

3 个答案:

答案 0 :(得分:1)

我认为此代码将出现在您的模型中。

public function owner(){
    return $this->belongsTo('App\Demotable2');
}

答案 1 :(得分:1)

当您尝试制作大部分雄辩的convention over configuration)时,您需要应用某些规则,当您使用时,您遇到的问题是命名foreign key。 :

public function owner(){
    return $this->belongsTo('App\Demotable2');
}

eloquent希望找到foreign key demo_id而不是demoId,当您更改外键的名称时,需要在关系中指定它,如下所示:

public function owner(){
    return $this->belongsTo('App\Demotable2', 'demoId', 'id');
}

你在这里阅读更多内容:http://laravel.com/docs/5.1/eloquent-relationships

答案 2 :(得分:0)

关系是在模型中定义的,而不是控制器。

App\Stuff.php

public function owner() {
    return $this->belongsTo(App\Demotable2::class);
}

运行此关系后,它会自动在owner_id表格中查找stuff。但是,您使用的是demoId。为此,您必须在关系中定义外键

public function owner() {
    return $this->belongsTo(App\Demotable2::class, 'demoId');
}