[英]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.