从查询构建器

时间:2017-07-13 11:30:03

标签: json laravel laravel-query-builder

我正在使用Query Builder从此查询中获取多个连接表的结果:

$products = DB::table('products as p')
              ->select(
                  'p.id',
                  'p.name',
                  'p.reference',
                  'p.price',
                  'i.path',
                  'i.name'
                )
              ->join('products_r_images as pri', 'pri.product_id', '=', 'p.id')
              ->join('images as i', 'i.id', '=', 'prd.image_id')
              ->get();

一个产品可以关联多个图像。

通过上述查询,我​​得到了这个结果:

[
    {
        id: 3,
        name: "Test",
        reference: "ref-test",
        price: 123,
        image_path: "product/product-3/",
        image_name: "product_1.jpg"
    },
    {
        id: 3,
        name: "Test",
        reference: "ref-test",
        price: 123,
        image_path: "product/product-3/",
        image_name: "product_2.jpg"
    }
]

正如您所看到的,两行是一个产品的返回,而我希望文档数据返回一行,如下所示:

[
    {
        product_id: 3,
        name: "Test",
        reference: "ref-test",
        price: 123,
        image_path: "product/product-3/",
        image_name: 
        [
            "product_1.jpg", "product_2.jpg"
        ]
    }
]

有没有办法直接使用Query Builder,或者需要其他处理?

1 个答案:

答案 0 :(得分:1)

如果您只想使用查询生成器,那么您应该能够:

$products = DB::table('products as p')
    ->select(
        'p.id',
        'p.name',
        'p.reference',
        'p.price',
        'i.path',
        'i.name'
    )
    ->join('products_r_images as pri', 'pri.product_id', '=', 'p.id')
    ->join('images as i', 'i.id', '=', 'prd.image_id')
    ->get()
    ->groupBy('id')
    ->map(function ($products) {

        $product = $products->first();
        $product->image_name = $products->pluck('image_name');

        return $product;
    });

希望这有帮助!

相关问题