【问题标题】:variables with relationships change during return返回期间具有关系的变量发生变化
【发布时间】:2019-08-10 00:03:20
【问题描述】:

我使用 Laravel。 我在 post 和 cmets 之间有关系。 我有$post,我想获得相关的$comments,只有值published 设置为true。 在控制器中我有:

$post     = Post::find($id);
$comments = $post->comments->where('published', 1)->get();

这里的变量comments 看起来很正常,但是当我这样做时:

return [
    'comments' => $comments,
    'post'     => $post,
];

我有来自 db 的所有 cmets,并在一个数组中与 cmets 进行连接。 例如

$post: 
id  24
title   "lorem"
body  "Lorem ipsum dolor sit amet, consectetur adipisicing elit. Blanditiis explicabo molestias obcaecati placeat vero. Alias aliquid consectetur, deserunt ducimus iure magnam minus molestias neque pariatur quidem sint temporibus totam vitae."
user_id 2
published   1
created_at  "2018-12-03 12:14:30"
updated_at  "2019-03-29 10:08:26"
comments    [
    1 [ ... ]
    2 [ ... ]
    n [ ... ] 
]

$comments {
 1 [ ... ]
 2 [ ... ]
 n [ ... ] 
}

那么我在哪里做错了?为什么会变?

model Comment.php

public function post()
{
    return $this->belongsTo(Post::class);
}

public function scopePublished($query)
{
    return $query->where('published', 1);
}

Post.php

public function comments()
{
    return $this->hasMany(Comment::class);
}

【问题讨论】:

  • 你为什么不使用eager-loading ?你可以查看我的帖子
  • 在我得到 cmets 之前,我已经有帖子了。我展示了我的逻辑的简化版本:D

标签: php laravel return


【解决方案1】:

试试这个

$post     = Post::with(['comments' => function($q) {
                     $q->where('published', 1); // or $q->published();
                 }])
                ->find($id);

您可以阅读Where with relationship

blade 文件中,可以使用 post 和 cmets 获取

{{ dd($post) }} //get post
{{ dd($post->comments) }} //get post related commnets 

【讨论】:

    【解决方案2】:
    $comments = $post->comments->where('published', 1)->get();
    

    检查已发布设置为 1 的 帖子。 要为任何帖子获取已发布的 cmets,请在您的 Post.php 中添加一个新关系,如下所示:

    public function publishedComments()
    {
        return $this->comments()->where('published', 1);
    }
    

    然后您可以像这样在控制器中使用它

    $comments = $post->publishedComments()->get();
    

    【讨论】:

    • 谢谢!这样可行!我不应该在 Comment.php 中使用我的 scopePublished 方法
    • 这也应该可以。只需在publishedComments()中使用它而不是where('published', 1)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-29
    • 2015-03-22
    • 1970-01-01
    • 2020-12-01
    相关资源
    最近更新 更多