Intro
Im havning some trubble getting the data on all the related elements. Im using Laravel as a REST backend service, exposing Json to the front-end javascript application.
Data structure
Consider I have the following tables:
+----------------+ +----------------+ +-------------+
|topics | |posts | |users |
+----------------+ +----------------+ +-------------+
|id: int | |id: int | |id: int |
|title: varchar | |content: varchar| |name: varchar|
|content: varchar| |user_id: int | +-------------+
|user_id: int | |topic_id: int |
+----------------+ +----------------+
A topic has 0 to many posts, and it has an author (user)
A post has one author (user)
UML: http://i58.servimg.com/u/f58/11/26/57/95/intrep10.png
Laravel Models
class User extends Eloquent {
protected $table = 'users';
public function topics() {
reutrn $this->hasMany('Topic');
}
public function posts() {
reutrn $this->hasMany('Post');
}
}
class Topic extends Eloquent {
protected $table = 'topics';
public function posts() {
return $this->hasMany('Post');
}
public function author() {
return $this->hasOne('User', 'id');
}
}
class Post extends Eloquent {
protected $table = 'posts';
public function topic() {
return $this->belongsTo('Topic');
}
public function author() {
return $this->hasOne('User', 'id');
}
}
Controller
return Topic::where('id', '=', $topicId)
->with('author', 'posts.author')
->get();
Output
[{
id: 1,
title: "My Topic",
content: "With opinions about the darkside",
user_id: 1,
created_at: "2014-03-06",
updated_at: "2014-03-06",
author: {
id: 1,
name: "JamesBond",
created_at: "2014-03-06",
updated_at: "2014-03-06",
},
posts: [{
id: 1,
content: "Reply 1 on topic 1",
user_id: 1,
created_at: "2014-03-06",
updated_at: "2014-03-06",
author: {
id: 1,
name: "JamesBond",
created_at: "2014-03-06",
updated_at: "2014-03-06",
},
},
{
id: 2,
content: "Reply 2 on topic 1",
user_id: 1,
created_at: "2014-03-06",
updated_at: "2014-03-06",
author: null,
}]
}]
Question
As you can see of the jsoncode, both the posts are created by the same user (with id 1), but only the first has the author object on it. Any pointers on how to figure out my problem would be perfect.
Disclaimer
This is a striped down version of my project, as I dont want to spam the question with information. If I lack serten elements to the question, I will be happy to supply it.
Solution
My model mapping was off.
public function author() {
return $this->belongsTo('User', 'user_id', 'id');
}
makes sure that its the user_id its looking for in the posts table, up against the id column in the users table
SELECT * FROM users WHERE id = posts.user_id;