【问题标题】:return related data as an array from sql (left outer) LARAVEL从 sql(左外)LARAVEL 以数组形式返回相关数据
【发布时间】:2018-03-03 00:44:37
【问题描述】:

我已查询此查询,该查询将相关图像返回到评论

  return    $comments = \DB::table('comments')->select('comments.comment','comments.user_name','comments.shop_name',
            'comments.rating','comments.created_at','comments_images.images')->
        join('comments_images','comments.id','=','comments_images.comment_id','left outer')
        ->where('comments.product_id', '=', "11644254552")->
orderBy(\DB::raw('-`images`'), 'desc')->get();

它返回这样的结果

{

comment: "fdsfdsfsdffddsffds",
user_name: "ahmaf",
shop_name: "example.com",
rating: "4",
created_at: "2017-09-19 02:14:41",
images: https://example.com/kf/UT8.1.cX3XaXXagOFbX5.jpg
},
-{
comment: "fdsfdsfsdffddsffds",
user_name: "ahmaf",
shop_name: "example.com",
rating: "4",
created_at: "2017-09-19 02:14:41",
images: https://example.com/kf/UT81WzoX3BXXXagOFbXs.jpg
},
-{
comment: "sdfdsfdssfd",
user_name: "fdsfds",
shop_name: "example2.myshopify.com",
rating: "5",
created_at: "2017-09-19 02:12:25",
images: null
}

如您所见,前两行是重复的,我希望它们像这样返回

comment: "fdsfdsfsdffddsffds",
user_name: "ahmaf",
shop_name: "example.com",
rating: "4",
created_at: "2017-09-19 02:14:41",
images:{
 0: https://example.com/kf/UT8.1.cX3XaXXagOFbX5.jpg
 1: https://example.com/kf/UT81WzoX3BXXXagOFbXs.jpg
}
},

-{
comment: "sdfdsfdssfd",
user_name: "fdsfds",
shop_name: "example2.myshopify.com",
rating: "5",
created_at: "2017-09-19 02:12:25",
images: null
}

这可能吗?将它们返回以收集而不是为每个相关数据创建新行。


我尝试使用它,但我无法使用 cmets_images 表中的 orderBy 图像,它仅适用于 cmets 中的列

$comments = Comment::where('product_id', '=', "11644215052")->with([
        'images' => function ($query)
        {
            $query->orderBy('images', 'desc');
        },
    ])->paginate(30);

【问题讨论】:

  • 尝试添加->groupBy('comments.id')->get();!!
  • groupBy 不起作用,如果我这样做,我将不得不在其中添加所有列,否则它将返回错误,因此它不会返回所有记录。我只想将重复的行组合在一起

标签: php mysql sql laravel laravel-5


【解决方案1】:

您正在寻找父/子关系结果。使用平行结果集您不会得到它。看看将 laravel 模型与子关系一起使用。

https://laravel.com/docs/5.5/eloquent-relationships#querying-relations

【讨论】:

  • 我知道所有这些,我可以使用 with (eager load) 来一起返回数据,但是我将无法使用 orderBy 所以我必须使用连接,但我如果没有急切的负载,找不到解决方案
  • 我不使用 Laravel 5,但我知道你可以设置与 ordering 的关系。 stackoverflow.com/questions/18143061/…
  • 您可以,但不能使用(急切的负载)您不能根据另一个表中的列进行排序。就我而言,我无法使用 cmets_images 表中的列对它们进行排序。
  • 使用 Laravel 4,我正在这样做。不过我还没有和 5 合作过。
  • 很好,我不相信他们两个之间有很大的区别,所以你能帮我检查一下这段代码,也许我做错了什么。我编辑了问题。
猜你喜欢
  • 2017-04-04
  • 2021-08-20
  • 1970-01-01
  • 1970-01-01
  • 2014-05-01
  • 1970-01-01
  • 2021-06-04
  • 2021-03-06
  • 2010-12-05
相关资源
最近更新 更多