Reputation: 3901
I have two tables, items and users. A User can have multiple Items and an Item can be owned by one User.
My two tables have many fields but are linked by:
Item
----
ownerID
User
----
id
These are the fields that link the two tables together and they are set in my database with a foreign key.
Here is a shortened version of the two models:
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');
}
}
So, I want to get all of my Items and eager load the owner. This is my code in my Controller:
class ItemsController extends BaseController {
public function all(){
$items = Item::with('owner')->get();
return $items;
}
}
(I am returning $items
so I can debug the output)
However, this is what I get as my output:
[
{
"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"
}
]
I don't understand why owner is null? User ID 1 exists in my database so why is it null?
Upvotes: 1
Views: 997
Reputation: 146191
According to your function in Item
public function owner()
{
return $this->belongsTo('User','id');
}
It indicates that, the foreign key
in the items
table is id
which is being used for relationship with users
table but you have used ownerId
as the foreign key
in the items
table which is the primary key
of users
table.
So, it should be
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');
}
While using belongsTo/reverse
the second argument passed to the function is the referencing key (child-key/local-key) in the current table and here, items
is the current table, which has the referencing key ownerId
as it's local-key
which relates to the id
field of users
table.
Upvotes: 2
Reputation: 6605
Try this
class Item extends Eloquent {
public function owner()
{
return $this->belongsTo('User','ownerID');
}
}
Upvotes: 0