【问题标题】:Is there an easier way to iterate through a list of objects properties in Laravel有没有更简单的方法来遍历 Laravel 中的对象属性列表
【发布时间】:2015-01-08 03:16:40
【问题描述】:

我有一个 Laravel 应用程序,我在其中使用了一些感觉非常不直观的代码。

在代码中,我返回一个对象列表 ($occupied),它们都具有“属性”列。然后我继续创建一个对象列表的数组“属性” ($occupiedproperty) 只是为了在 whereNotIn 调用中使用它。

    if ($occupied = Residency::currentResidents()){

        // Here is the pointless part //////
        $occupiedproperty = array();
        foreach ($occupied as $occ) {
            array_push($occupiedproperty, $occ->property);
        }
        ///////////////////////////////////

        return Property::whereNotIn('id', $occupiedproperty)->get();
    }

这段代码可以很好地完成这项工作,但是当我已经有一个对象列表时创建一个新数组似乎很懒惰。我尝试查看 eloquent 的文档,但我无法弄清楚。

我需要能够访问$occupied 的“属性”列,这样我才能运行whereNotIn('id', $occupied->property) 之类的东西

谢谢

【问题讨论】:

    标签: php laravel properties eloquent


    【解决方案1】:

    目前无法对其进行测试,但这应该可以工作(即使不强制转换为数组 $occupied 集合也应该可以工作):

    $occupiedProperties = array_pluck((array)$occupied, 'property');
    

    它使用array_pluck() 辅助方法:http://laravel.com/docs/4.2/helpers#arrays

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-09-30
      • 2021-11-08
      • 2020-03-19
      • 2018-12-12
      • 2017-06-25
      • 2021-12-14
      • 1970-01-01
      相关资源
      最近更新 更多