Laravel: 通过键数组获取模型属性
Laravel: Get model attributes by key array
我正在尝试通过键数组访问模型属性。所需的功能类似于 $model->getAttribute('name')
,但接受数组而不是字符串。
假设我们有一个模型,其属性名称为 'A',年龄为 2,blood_type 为 'B'。
$attributesToPull = ['name', 'age'];
$model->getAttributes($attributesToPull);
// returns ['A', 2]
我查看了 Laravel 文档,但找不到任何合适的内容。
结果不需要直接来自模型,可以使用 $model->getAttributes()
将它们拉入自己的关联数组,然后使用原生 PHP 数组函数,例如 array_intersect
过滤结果,但即使那样我似乎也找不到一个函数可以让我用索引数组过滤关联数组。
有谁知道我该怎么做,最好不使用循环或回调?答案可以很开放,它可以 return 一个集合或一个数组,并使用模型属性的关联数组或调用模型本身的函数。
模型有一个 only
方法:
$model->only($attributesToPull);
我正在尝试通过键数组访问模型属性。所需的功能类似于 $model->getAttribute('name')
,但接受数组而不是字符串。
假设我们有一个模型,其属性名称为 'A',年龄为 2,blood_type 为 'B'。
$attributesToPull = ['name', 'age'];
$model->getAttributes($attributesToPull);
// returns ['A', 2]
我查看了 Laravel 文档,但找不到任何合适的内容。
结果不需要直接来自模型,可以使用 $model->getAttributes()
将它们拉入自己的关联数组,然后使用原生 PHP 数组函数,例如 array_intersect
过滤结果,但即使那样我似乎也找不到一个函数可以让我用索引数组过滤关联数组。
有谁知道我该怎么做,最好不使用循环或回调?答案可以很开放,它可以 return 一个集合或一个数组,并使用模型属性的关联数组或调用模型本身的函数。
模型有一个 only
方法:
$model->only($attributesToPull);