【问题标题】:How to access a field in relation in eloquent orm如何以雄辩的形式访问相关的字段
【发布时间】:2020-10-13 05:40:12
【问题描述】:

我编写了这段代码来获取带有图片和类别的产品信息:

 ->where('category_id', 5)
            ->with('类别', '文件')->get();

我的结果是:

{
        "id": 2,
        "name": "test",
        "price": 13000,
        "description": "some text ...",
        "shop_id": 1,
        "rate": 0,
        "category_id": 5,
        "discount_percent": 20,
        "category": {
            "id": 5,
            "name": "cat1",
            "shop_id": 1
        },
        "files": [
            {
                "id": 99,
                "disk_name": "5ef1af07d6d98778754621.jpg",
                "file_name": "13330983_xl.jpg",
                "file_size": 69813,
                "content_type": "image/jpeg",
                "title": null,
                "description": null,
                "field": "product_gallery",
                "sort_order": 99,
                "created_at": "2020-06-23 07:28:07",
                "updated_at": "2020-06-23 07:28:10",
                "path":...... storage/app/uploads/public/5ef/1af/07d/5ef1af07d6d98778754621.jpg",
                "extension": "jpg"
            }
        ]
    }

现在我想访问路径字段,我该怎么做? 我使用这种方式进行访问,但我没有得到结果:

products[0].files[0].path

【问题讨论】:

  • Eloquent 返回对象,你必须访问该对象请使用 -> 而不是 .
  • 我使用树枝标签 {{ products[0].files[0].path }} @PankajBisht
  • 试试看data_get($products[, '0.files.0.path'')
  • 当然,但你正在使用 ->get() 添加 ->toArray() 到它

标签: database laravel eloquent relationship data-retrieval


【解决方案1】:

你应该使用 toArray() 函数来转换这样的数据

->where('category_id', 5)
->with('category', 'Files')->get()->toArray();

然后访问

products[0]['files'][0]['path']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-08-22
    • 2020-12-13
    • 2021-07-06
    • 2015-05-08
    • 2021-02-21
    • 1970-01-01
    • 1970-01-01
    • 2019-03-17
    相关资源
    最近更新 更多