【问题标题】:How do I retrieve image full url from database where column contain array of images?如何从列包含图像数组的数据库中检索图像完整 url?
【发布时间】:2020-09-24 09:59:05
【问题描述】:

我在数据库列名图像中存储了一个图像数组,如下所示:

'images' => [
    '80011701010550.jpg',
    '80011701010550_3.jpg',
    '80011701010550_4.jpg'
],

我是这样做的:

$list = App\ProductTemplate::select('product_templates_id','name', 'keywords', 'images')->get();

它给了我这样的结果:

"list": [{
    "product_templates_id": 1,
    "name": "Daawat Brown Basmati Rice",
    "keywords": "basmati Daawat rice chawal tandul tandool",
    "images": [
        "60011805049946.jpg"
    ]
}]

我只想检索包含第一张图片的完整 URL 的所有列表。我想将此完整的 URL 属性附加到一个列表中。那么如何使用 Laravel 实现这一点呢?

我想要这样的结果:

"list": [{
    "product_templates_id": 1,
    "name": "Daawat Brown Basmati Rice",
    "keywords": "basmati Daawat rice chawal tandul tandool",
    "images_full_url": "http:://localhost/images/60011805049946.jpg"
}]

请帮帮我。

【问题讨论】:

  • 你可以在laravel中使用eloquentmutarorsaccessors功能。
  • 为什么不在输出图像名称的地方简单地添加 URL?因为无论如何你都在改变整个东西(从图像数组到单个值images_full_url),在那里添加这样的逻辑应该不会太难
  • 使用 mutators 解决的问题

标签: php laravel


【解决方案1】:

你可以使用like 在ProductTemplate.php模型中

protected $appends = ['images_full_url'];

function getImageFullUrlAttribute()
{
    $fullUrl = [];
    foreach ($this->images as $image) {
        array_push($fullUrl, asset('images/' . $image));
    }
    return $fullUrl;
}

它将images_full_url 附加到集合中

参考链接https://laravel.com/docs/8.x/eloquent-serialization#appending-values-to-json

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-25
    • 1970-01-01
    • 2021-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-08
    • 2013-06-27
    相关资源
    最近更新 更多