i'm starting to learn laravel 4 but i'm still far, I already took a look ORM and relations so i have the following question:
I have 3 type of table: users, posts, content_post and i would like have the ralations having like result all the posts and contents about a user.
users table
id | userame | name |
1 Ellie Elen
2 Pol Paul
posts table
id | id_poster |
1 1
2 1
3 2
content_post
id | id_post | text | link | video | photo
1 1 hey NULL NULL tree.png
2 2 woo http NULL NULL
3 3 Hi NULL NULL NULL
php
class User Extends Eloquent {
function posts() {
return $this->belongsToMany('posts','id_poster');
}
}
class Posts Extends Eloquent {
function user() {
return $this->HasOne('users');
}
function content() {
return $this->HasOne('content_post','id_post');
}
}
class Content Extends Eloquent {
function posts() {
return $this->HasOne('posts');
}
}
?>
and then i'll go to get the results like so but it doesn't show me nothing
$user = new User;
$user = $user->find(1)->posts();
Where i'm doing error?
You should declare relations in this way:
class User Extends Eloquent {
function posts() {
return $this->hasMany('Posts','id_poster'); /* Note that 'Posts' is model name - not table */
}
}
class Posts Extends Eloquent {
function user() {
return $this->belongsTo('User', 'id_poster');
}
function content() {
return $this->hasOne('Content','id_post');
}
}
class Content Extends Eloquent {
function posts() {
return $this->belongsTo('Posts', 'id_post');
}
}
After you can try to request user with posts:
$user = new User();
$user = $user->with('posts.content')->find(1);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.