【问题标题】:How to get array in array with laravel and mysql database?如何使用 laravel 和 mysql 数据库获取数组中的数组?
【发布时间】:2021-11-07 04:14:17
【问题描述】:

我在后端使用 Laravel (PHP) 和 MySQL。我正在创建用于设置和从数据库获取信息的方法。这些信息以 json 格式发送到前端。

我可以发送如下表格信息:

[
    {
        "id": 4,
        "name": "Max"
    },
    {
        "id": 5,
        "name": "Eric"
    }
]

为此,我使用 laravel 方法,例如:DB::table('user')->select('user.id', 'user.name')->get();

但是我做前端的朋友想要下面的 json 代码:

[
    {
        "id": 4,
        "name": "Max"
        "specific_user_price":{
                                "S":5.00,
                                "M":6.00,
                                "XL":8.00
                              }
    },
    {
        "id": 5,
        "name": "Eric"
        "specific_user_price":{
                                "S":5.50,
                                "M":10.00,
                                "XL":15.00
                              }
    }
]

"specific_user_price 是一个表,"S"、"M"、"XL" 是根据用户具有不同值的列。我不知道如何在查询中创建 specific_user_price 作为数组。我可以使用group_concat 但他需要上面显示的 json。

我的想法是在用户“size S price”、“size M price”和“size XL price”中创建额外的列。但是我的朋友希望这些值作为一个自己的数组组,因为有些用户只能访问一种大小,所以他会得到空值。

任何想法我可以使用 PHP 或 Laravel 中的哪种方法?或者是否有一种 MySQL 方法可以在查询中创建这样的东西?

【问题讨论】:

  • 你可以使用 laravel 资源:laravel.com/docs/8.x/eloquent-resources 这样你可以设置任何格式的响应
  • 我假设价格表有一个 user_id?
  • 对于 specific_user_price 您应该在用户和价格之间建立任何关系

标签: php mysql laravel


【解决方案1】:

首先使用模型,开箱即用更容易使用。像这样定义您的 User 模型,并与价格建立关系。

use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    public function specificUserPrice() {
        return $this->hasOne(UserPrice::class);
    }
}

您还需要定义 UserPrice 模型。

use Illuminate\Database\Eloquent\Model;

class SpecificUserPrice extends Model
{
}

Laravel 自动转换模型,您可以在控制器中使用以下代码。

public function index()
{
    return User::with('specificUserPrice')->get();
}

【讨论】:

    【解决方案2】:

    DB::table('user')->select(['id', 4],['name','max'])->get();

    【讨论】:

      【解决方案3】:

      DB::table('user')[0]->get()

      这将为您获取数组中的第一个元素

      【讨论】:

        猜你喜欢
        • 2021-03-24
        • 2018-11-10
        • 1970-01-01
        • 2020-02-29
        • 2019-03-04
        • 2021-03-12
        • 2015-03-25
        • 1970-01-01
        • 2021-10-03
        相关资源
        最近更新 更多