草庐IT

php - 在 Laravel get() 查询生成器中附加两个数组

coder 2023-10-25 原文

我必须在 Laravel 中查询。首先,获得一个职位。第二,获取所有评论。我的问题是,我无法在 Laravel 查询生成器中正确附加 get() 的两个数组输出。

当我尝试加入他们时,该帖子出现了 3 次,因为我对该帖子有 3 条评论。因此,我没有加入,而是尝试 array_push 他们。现在输出是这样的。

[
    {
    "id": 44,
    "image": "9178hello.jpg",
    "description": "Lorem ipsum dolor sit amit!",
    "address": "internet",
    "lat": 45.435,
    "long": 2312.3,
    "created_at": "1 hour ago"
    },
    [
        {
            "comment": "my comment.... my comment 1.....",
            "created_at": "2015-01-11 17:24:27"
        },
        {
            "comment": "my comment.... my comment 2.....",
            "created_at": "2015-01-11 17:24:29"
        },
        {
            "comment": "my comment.... my comment 3.....",
            "created_at": "2015-01-11 17:24:30"
        }
    ]
]

我怎样才能让它成为:

[
    {
    "id": 44,
    "image": "9178hello.jpg",
    "description": "Lorem ipsum dolor sit amit!",
    "address": "internet",
    "lat": 45.435,
    "long": 2312.3,
    "created_at": "1 hour ago",
    "comments" : { 
           list all the comments here...
         }
    }
]

这是查询:

    $disaster = Disaster::where('name', '=', $name)->first(['id']);

    $post =  DB::table('posts')
                ->join('locations', 'locations.id', '=', 'posts.location')
                ->join('users', 'users.id', '=', 'posts.user_id')
                ->select('posts.id', 'posts.image', 'posts.description', 'locations.address', 'locations.lat', 'locations.long', 'posts.user_id', 'users.firstname', 'users.lastname', 'posts.created_at')
                ->where('posts.disaster_id', '=', $disaster->id)
                ->where('posts.id', '=', $id)
                ->get();

    if (empty($post)) {
        return ['error' => 'no post found'];
    }

    $post[0]->created_at = Carbon::parse($post[0]->created_at)->diffForHumans();

    $comments = DB::table('comments')
                  ->select('comment', 'created_at')
                  ->where('post_id', '=', $post[0]->id)
                  ->get();

    array_push($post, $comments);

    return $post;

最佳答案

你可以这样做

$array = array_merge($post, array('comments' => $comments));

文档:array_merge 这会将带有 comments key 的评论附加到 post 数组。

既然你在使用 Laravel,为什么不使用 Eloquent 关系呢?只需在帖子和评论之间建立一对多关系,然后以任何您想要的方式获取它们。

阅读Laravel Eloquent Relations

关于php - 在 Laravel get() 查询生成器中附加两个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27886142/

有关php - 在 Laravel get() 查询生成器中附加两个数组的更多相关文章

  1. ruby - 使用 RubyZip 生成 ZIP 文件时设置压缩级别 - 2

    我有一个Ruby程序,它使用rubyzip压缩XML文件的目录树。gem。我的问题是文件开始变得很重,我想提高压缩级别,因为压缩时间不是问题。我在rubyzipdocumentation中找不到一种为创建的ZIP文件指定压缩级别的方法。有人知道如何更改此设置吗?是否有另一个允许指定压缩级别的Ruby库? 最佳答案 这是我通过查看ruby​​zip内部创建的代码。level=Zlib::BEST_COMPRESSIONZip::ZipOutputStream.open(zip_file)do|zip|Dir.glob("**/*")d

  2. ruby - ECONNRESET (Whois::ConnectionError) - 尝试在 Ruby 中查询 Whois 时出错 - 2

    我正在用Ruby编写一个简单的程序来检查域列表是否被占用。基本上它循环遍历列表,并使用以下函数进行检查。require'rubygems'require'whois'defcheck_domain(domain)c=Whois::Client.newc.query("google.com").available?end程序不断出错(即使我在google.com中进行硬编码),并打印以下消息。鉴于该程序非常简单,我已经没有什么想法了-有什么建议吗?/Library/Ruby/Gems/1.8/gems/whois-2.0.2/lib/whois/server/adapters/base.

  3. ruby-on-rails - 在 Ruby 中循环遍历多个数组 - 2

    我有多个ActiveRecord子类Item的实例数组,我需要根据最早的事件循环打印。在这种情况下,我需要打印付款和维护日期,如下所示:ItemAmaintenancerequiredin5daysItemBpaymentrequiredin6daysItemApaymentrequiredin7daysItemBmaintenancerequiredin8days我目前有两个查询,用于查找maintenance和payment项目(非排他性查询),并输出如下内容:paymentrequiredin...maintenancerequiredin...有什么方法可以改善上述(丑陋的)代

  4. ruby - 多次弹出/移动 ruby​​ 数组 - 2

    我的代码目前看起来像这样numbers=[1,2,3,4,5]defpop_threepop=[]3.times{pop有没有办法在一行中完成pop_three方法中的内容?我基本上想做类似numbers.slice(0,3)的事情,但要删除切片中的数组项。嗯...嗯,我想我刚刚意识到我可以试试slice! 最佳答案 是numbers.pop(3)或者numbers.shift(3)如果你想要另一边。 关于ruby-多次弹出/移动ruby​​数组,我们在StackOverflow上找到一

  5. ruby - 将数组的内容转换为 int - 2

    我需要读入一个包含数字列表的文件。此代码读取文件并将其放入二维数组中。现在我需要获取数组中所有数字的平均值,但我需要将数组的内容更改为int。有什么想法可以将to_i方法放在哪里吗?ClassTerraindefinitializefile_name@input=IO.readlines(file_name)#readinfile@size=@input[0].to_i@land=[@size]x=1whilex 最佳答案 只需将数组映射为整数:@land边注如果你想得到一条线的平均值,你可以这样做:values=@input[x]

  6. ruby-on-rails - 如何在 ruby​​ 中使用两个参数异步运行 exe? - 2

    exe应该在我打开页面时运行。异步进程需要运行。有什么方法可以在ruby​​中使用两个参数异步运行exe吗?我已经尝试过ruby​​命令-system()、exec()但它正在等待过程完成。我需要用参数启动exe,无需等待进程完成是否有任何ruby​​gems会支持我的问题? 最佳答案 您可以使用Process.spawn和Process.wait2:pid=Process.spawn'your.exe','--option'#Later...pid,status=Process.wait2pid您的程序将作为解释器的子进程执行。除

  7. ruby - 在 jRuby 中使用 'fork' 生成进程的替代方案? - 2

    在MRIRuby中我可以这样做:deftransferinternal_server=self.init_serverpid=forkdointernal_server.runend#Maketheserverprocessrunindependently.Process.detach(pid)internal_client=self.init_client#Dootherstuffwithconnectingtointernal_server...internal_client.post('somedata')ensure#KillserverProcess.kill('KILL',

  8. ruby - 通过 erb 模板输出 ruby​​ 数组 - 2

    我正在使用puppet为ruby​​程序提供一组常量。我需要提供一组主机名,我的程序将对其进行迭代。在我之前使用的bash脚本中,我只是将它作为一个puppet变量hosts=>"host1,host2"我将其提供给bash脚本作为HOSTS=显然这对ruby​​不太适用——我需要它的格式hosts=["host1","host2"]自从phosts和putsmy_array.inspect提供输出["host1","host2"]我希望使用其中之一。不幸的是,我终其一生都无法弄清楚如何让它发挥作用。我尝试了以下各项:我发现某处他们指出我需要在函数调用前放置“function_”……这

  9. ruby - 检查数组是否在增加 - 2

    这个问题在这里已经有了答案:Checktoseeifanarrayisalreadysorted?(8个答案)关闭9年前。我只是想知道是否有办法检查数组是否在增加?这是我的解决方案,但我正在寻找更漂亮的方法:n=-1@arr.flatten.each{|e|returnfalseife

  10. ruby - 如何使用 Ruby aws/s3 Gem 生成安全 URL 以从 s3 下载文件 - 2

    我正在编写一个小脚本来定位aws存储桶中的特定文件,并创建一个临时验证的url以发送给同事。(理想情况下,这将创建类似于在控制台上右键单击存储桶中的文件并复制链接地址的结果)。我研究过回形针,它似乎不符合这个标准,但我可能只是不知道它的全部功能。我尝试了以下方法:defauthenticated_url(file_name,bucket)AWS::S3::S3Object.url_for(file_name,bucket,:secure=>true,:expires=>20*60)end产生这种类型的结果:...-1.amazonaws.com/file_path/file.zip.A

随机推荐