[英]Relations Laravel 4 from 3 tables
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: 我开始学习laravel 4,但是我仍然很远,我已经看过ORM和关系,所以我有以下问题:
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. 我有3种类型的表:users,posts,content_post,我希望所有的聚会和内容都与用户有关。
users table 用户表
id | userame | name |
1 Ellie Elen
2 Pol Paul
posts table 帖子表
id | id_poster |
1 1
2 1
3 2
content_post 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 的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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.