douyu9159 2014-12-22 21:57
浏览 21
已采纳

too long

I have this in a "Product" model to map the one to many relationship between a product and a barcode:

public function barcodes(){
    return $this->hasMany('Barcode', 'productId', 'id')->select(['barcode', 'productId']);
}

Next, this code gives me not only the product, but also each barcode in an array of objects.

public function search(){
    $results = Product::with('barcodes')->where('name', 'LIKE', 'theQueryString')->get();
    return Response::json($return);
}

This is an example output:

{
    "results": [
        {
            "id": 1,
            "name": "Warehouse Box",
            "created_at": "2034-12-14 06:57:52",
            "updated_at": "2064-12-14 06:27:52",
            "barcodes": [
                {
                    "barcode": "0750028400400",
                    "productId": 1
                },
                {
                    "barcode": "123456789",
                    "productId": 1
                }
            ]
        }
    ]
}

Instead of "barcodes" returning an array of objects, I want "barcodes" just to be an array of values.

Said another way, I want to return the value of the "barcode" column in each barcode object instead of the object itself.

Here is what I want it to look like:

{
    "results": [
        {
            "id": 1,
            "name": "Warehouse Box",
            "created_at": "2034-12-14 06:57:52",
            "updated_at": "2064-12-14 06:27:52",
            "barcodes": [
                "0750028400400",
                "123456789"
            ]
        }
    ]
}

Is there a quick and smart way of doing this in Laravel using Eloquent?

  • 写回答

2条回答 默认 最新

  • dpiw16824 2014-12-22 22:29
    关注

    There is the lists() which makes an array containing one property of each model in a collection. However the problem is that we have to do this for every result of the relation in the model. That would mean a loop in your controller. (and we don't want that right)

    Instead you can override toArray() (which will be called when you do Response::json()) in your model. In the code below, we override barcodes with the lists() result.

    public function toArray(){
        $array = parent::toArray();
        $array['barcodes'] = $this->barcodes->lists('barcode');
        return $array;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题