繁体   English   中英

Laravel hasMany as many hasOne

[英]Laravel hasMany as many hasOne

例如,我有 Post 和 Comment 模型。 当我加载 hasMany 关系时,我想为每个关系项获取单独的父项。

Post.php:

class Post extends Model
{
    public function comments()
    {
        return $this->hasMany('App\Comment');
    }
}

评论.php:

class Comment extends Model
{
    public function comments()
    {
        return $this->belongsTo('App\Post');
    }
}

当我加载带有评论的帖子时

Post::where('title', 'LIKE', search) 
    ->orWhereHas('comments', function ($query) use ($search) {
        $query->where('text', 'LIKE', $search) 
    })
    ->paginate();

结果看起来像这样

[
    {
        post_id: 1,
        comments: [
            {
                comment_id: 1
                post_id: 1
            },
            {
                comment_id: 2
                post_id: 1
            },
            {
                comment_id: 3
                post_id: 1
            },
        ]
    },
    ...
]

但我需要它看起来像这样(每个评论的单独帖子)。

[
    {
        post_id: 1,
        comments: [
            {
                comment_id: 1
                post_id: 1
            }
        ]
    },
    {
        post_id: 1,
        comments: [
            {
                comment_id: 2
                post_id: 1
            }
        ]
    },
    {
        post_id: 1,
        comments: [
            {
                comment_id: 3
                post_id: 1
            }
        ]
    },
    ...
]

我可以用 Laravel 做吗?

您现在正在检索带有评论的帖子,但据我了解,您实际上想从特定帖子中检索评论。

唯一的困难是指定从哪些帖子加载评论,但这可能会奏效:

$comments = Comment::whereHas('post', function($query) use ($ids) {
        $query->whereIn('post_id', $ids);
    })
    ->with('post')
    ->get();

(Comment 模型中的两个小错误需要先修复:将函数从 comments()重命名为 post()并将其更改为 $this this

这是一个简单的 foreach 来测试结果:

foreach ($comments as $comment) {
    echo 'Post ' . $comment->post->id . ' comment' . $comment->id . '<br>';
}

如果您绝对需要您在 JSON 数据中显示的格式的结果,则需要一些额外的工作,但没有必要这样做来获得您在评论中链接的图像中显示的输出。

更新(因为用户改变了问题):

通过评论文本(而不是 post-id)搜索使查询更加容易; 现在根本不需要嵌套查询:

$comments = Comment::where('text', 'like', '%' . $search . '%')
        ->with('post')
        ->get();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM