[英]Laravel 4 eager loading issues with relationship
我有两个表,项目和用户。 一个用户可以有多个项目,而一个项目可以由一个用户拥有。
我的两个表有很多字段,但通过以下方式链接:
Item
----
ownerID
User
----
id
这些是将两个表链接在一起的字段,它们在我的数据库中用外键设置。
这是两个模型的简化版本:
class Item extends Eloquent {
public function owner()
{
return $this->belongsTo('User','id');
}
}
class User extends Eloquent implements UserInterface, RemindableInterface {
public function items()
{
return $this->hasMany('Item', 'ownerID');
}
}
因此,我想获取所有项目并渴望加载所有者。 这是我的控制器中的代码:
class ItemsController extends BaseController {
public function all(){
$items = Item::with('owner')->get();
return $items;
}
}
(我返回$items
以便调试输出)
但是,这就是我的输出:
[
{
"active":"1",
"categoryID":"1",
"created_at":"0000-00-00 00:00:00",
"description":"Just a test item",
"endDate":"2014-03-01 21:46:07",
"id":"32",
"name":"Test Item",
"owner":null,
"ownerID":"1",
"section":"0",
"updated_at":"0000-00-00 00:00:00"
}
]
我不明白为什么所有者为空? 用户ID 1存在于我的数据库中,为什么它为null?
根据您在Item
的功能
public function owner()
{
return $this->belongsTo('User','id');
}
它表示items
表中的foreign key
是用于与users
表建立关系的id
,但是您已将ownerId
用作items
表中的foreign key
,这是users
表的primary key
。
所以应该
public function owner()
{
// This model (child) with a local-key/field ownerId
// in it's corresponding table(items) belongs to/relates to the
// user model (parent) with primary-key id in corresponding (users) table
return $this->belongsTo('User','ownerID');
}
在使用belongsTo/reverse
,传递给该函数的第二个参数是当前表中的引用键(子键/本地键),此处的items
是当前表,其引用键ownerId
是它的local-key
,与users
表的id
字段相关。
尝试这个
class Item extends Eloquent {
public function owner()
{
return $this->belongsTo('User','ownerID');
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.