我开始学习 laravel 4 但我还很远,我已经看过 ORM 和关系所以我有以下问题:
我有 3 种类型的表:users、posts、content_post,我希望所有关于用户的帖子和内容都具有类似的结果。
用户表
id | userame | name |
1 Ellie Elen
2 Pol Paul
帖子表
id | id_poster |
1 1
2 1
3 2
内容发布
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');
}
}
?>
然后我会像这样去获取结果,但它没有显示任何内容
$user = new User;
$user = $user->find(1)->posts();
我在哪里做错了?
最佳答案
你应该这样声明关系:
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');
}
}
在您可以尝试通过帖子请求用户之后:
$user = new User();
$user = $user->with('posts.content')->find(1);
关于php - 来自 3 个表的关系 Laravel 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20610773/