gpt4 book ai didi

php - 来自 3 个表的关系 Laravel 4

转载 作者:太空宇宙 更新时间:2023-11-03 12:19:53 25 4
gpt4 key购买 nike

我开始学习 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com