【问题标题】:Get certain attributes from an Eloquent model when converting to an Array in Laravel在 Laravel 中转换为数组时从 Eloquent 模型中获取某些属性
【发布时间】:2020-07-31 01:36:02
【问题描述】:

我有一个模型(例如User)。

我可以像这样轻松地将它转换为数组:

$user->toArray()

但是,这给出了所有属性。我只想要属性xyz

我们可以使用模型的hiddenvisible 属性来隐藏/显示值,如下所述:https://laravel.com/docs/5.4/eloquent-serialization#hiding-attributes-from-json

但是,我不想使用它,因为这更像是一种一次性的情况。不是经常发生。

pluck 方法是理想的,但这仅适用于集合,而不适用于模型。

【问题讨论】:

标签: laravel laravel-5 laravel-5.2 laravel-5.1 laravel-5.3


【解决方案1】:

您可以覆盖toArray() 方法,并允许它获取您希望返回的字段数组。

public function toArray(array $fields = [])
{
    // Get the full, original array.
    $original = parent::toArray();

    // If no fields are specified, return the original array.
    // This ensures that all existing code works the same
    // way as before.
    if (empty($fields)) {
        return $original;
    }

    // Return an array containing only those fields specified
    // by the input parameter.
    return array_intersect_key($original, array_flip($fields));
}

在您的用户模型中重写此方法后,您现在可以拥有以下代码:

// Will return an array with all the fields.
$full = $user->toArray();

// Will return an array with only x, y, and z fields.
$partial = $user->toArray(['x', 'y', 'z']);

注意:由于这会调用父级 toArray() 方法,因此此覆盖的方法仍将遵循 $hidden 属性。因此,如果 y 隐藏,并且您调用 $user->toArray(['x', 'y', 'z']);,则结果数组将不包含 y 值。

【讨论】:

    【解决方案2】:

    您现在可以使用 only 方法,我相信至少从 Laravel 5 开始可用,它已经返回一个数组:

    $user->only(['x', 'y', 'x']);
    

    $user->only('x', 'y', 'x');
    // ['x' => 1, 'y' => 2, 'x' => 3]
    

    【讨论】:

      猜你喜欢
      • 2021-02-13
      • 2016-01-06
      • 2021-11-19
      • 1970-01-01
      • 1970-01-01
      • 2014-06-17
      • 1970-01-01
      • 2013-12-02
      • 1970-01-01
      相关资源
      最近更新 更多