【问题标题】:Laravel Eloquent hasMany relationshipLaravel Eloquent 有很多关系
【发布时间】:2015-08-05 10:10:58
【问题描述】:

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

用户模型

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 创建的。

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

【问题讨论】:

  • 如果你刚开始使用 Laravel,你应该使用最新版本,在撰写本文时是 5.0。
  • @lukasgeiter 这个项目的要求是 4.0。不过感谢您的评论。干杯!!

标签: php laravel eloquent


【解决方案1】:

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

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

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

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

此外,为了将来参考,将关系作为属性访问将返回一个集合,而将关系作为方法访问将返回一个查询生成器实例。所以$user->posts$user->posts()->get() 是一样的。

【讨论】:

  • 嘿@Bogdan 谢谢你的回复。这就是我正在做的事情。 $post->comment AS $comment。我可以得到评论,但我怎样才能得到用户。现在我得到this comment by user1; this comment by user1,因为他们俩的评论都来自两个不同的user,称为user1user 2
【解决方案2】:

您想获取发表评论的用户,因此请从评论对象中获取该用户。

试试这个

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

foreach ($posts as $post) {
    foreach ($post->comments as $comment) {
        echo $comment->commentcontent;
        echo $comment->users;
    }
}

【讨论】:

  • 嗨@wiseodd $comment->用户将收到错误Undefined Property
  • 嗯,这取决于你在Comment 模型中的关系。因为在您上面的问题中,您创建了评论 - 与 users() 的用户关系,您必须使用 $comment->users$comment->users()->get() 访问它
  • 这对我很有帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-20
  • 1970-01-01
  • 2014-07-10
  • 2015-05-19
  • 2016-10-12
  • 2019-06-13
相关资源
最近更新 更多