【发布时间】:2014-02-01 22:17:18
【问题描述】:
我有两个表,项目和用户。一个用户可以有多个项目,一个项目可以由一个用户拥有。
我的两个表有很多字段,但通过以下方式链接:
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 存在于我的数据库中,为什么它为空?
【问题讨论】:
标签: php mysql laravel laravel-4 eloquent