我有两个表,项目和用户。一个用户可以拥有多个项目,一个项目可以由一个用户拥有。
我的两个表有很多字段,但通过以下方式链接:
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');
}
}
所以,我想获取我所有的项目并急切加载所有者。这是我在 Controller 中的代码:
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"
}
]
我不明白为什么 owner 为空?用户 ID 1 存在于我的数据库中,为什么它为空?
最佳答案
根据你在Item
中的功能
public function owner()
{
return $this->belongsTo('User','id');
}
它表示,foreign key
在items
表是 id
用于与 users
的关系表,但你使用了 ownerId
作为foreign key
在items
表格是 primary key
的 users
表。
所以,应该是
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
时传递给函数的第二个参数是当前表中的引用键(child-key/local-key),这里是items
是当前表,它有引用键 ownerId
因为它是local-key
这与 id
有关领域users
表。
关于php - Laravel 4 急切加载关系问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21504379/