php - Laravel Eloquent 有很多关系

标签 php laravel eloquent

您好,我是 Laravel 新手,目前正在使用 Laravel 4.2。我正在尝试创建一个应用程序,其中有用户、帖子和评论表,并具有以下模型

用户模型

function posts() {

    return $this->hasMany('Post');
}


function comments(){

    return $this->hasMany('Comment');
}

发布模型

function users() {

    return $this->belongsTo('User');
}

function comments() {

    return $this->hasMany('Comment');
}

评论模型

function posts(){

    return $this->belongsTo('Post');
}

function users(){

    return $this->belongsTo('User');
}

我想要实现的目标:

用户的帖子和帖子评论

eg:: User1 -> Post one -> comment for post one

到目前为止我做了什么:::

$user = User::find(1);
$post = $user->posts()->get();

我可以获得帖子,但如何获得特定帖子的评论?

更新

感谢@Bogdan 的帮助,我能够获得用户的帖子和评论。但和往常一样,还有另一个问题。

我得到了什么:

 foreach($user->post AS $post) {

 foreach ($post->comment AS $comment ) {

 $comment->commentcontent; $user->uername;
}
}//first foreach

这就是我得到的

comment one by user1.
comment two by user1.

但实际上评论一是由 user1 创建的,评论二是由 user2 创建的。

感谢您提前提供的帮助。如果需要可以发布完整代码。

最佳答案

当您使用 $user->posts()->get() 检索用户的帖子时,您将获得 ModelsCollection ,您可以在其中使用 find 来获取您想要的特定帖子。然后,您可以像检索用户帖子一样检索帖子的评论:

$user = User::find(1);
$post = $user->posts()->find($postId);
$comments = $post->comments;

如果您想迭代整个帖子集合,您可以执行此操作并单独访问每个帖子的评论,而无需过滤特定帖子:

foreach ($user->posts as $post)
{
    $comments = $post->comments;
}

此外,为了将来引用,将关系作为属性访问将返回一个 Collection,而将关系作为方法访问将返回一个查询生成器实例。所以 $user->posts$user->posts()->get() 相同。

关于php - Laravel Eloquent 有很多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30412755/

相关文章:

php - 如何有条件地在 .htaccess 中或通过其他方式为特定请求设置 php ini 值

php - 在 Laravel 生产中完全禁用错误报告?

php - 把 Laravel Query 变成 Key Value?

php - Laravel Eloquent 集成到 Codeigniter 中

php - 使用套接字安全登录

php - 为以下四个表编写连接查询,如果满足某个条件则获取记录

mysql - 来自 hasmany 关系值的 Laravel 子查询值

php - Laravel:选择同一天创建的条目

php - 遥远的HasManyThrough

PHP 警告 : PHP Startup: Unable to load dynamic library '...' failed to map segment from shared object: Cannot allocate memory in Unknown on line 0