简体   繁体   English

使用收集 function 创建的 Laravel 集合未在私有属性上添加过滤器

[英]Laravel collection created with collect function is not adding filter on private property

I have used the collect(array) function on $contacts to convert to the collection and use where condition to find the object on criteria of contactId我已经使用 $contacts 上的 collect(array) function 转换为集合并使用 where 条件在 contactId 的条件下找到 object

class Contact {
    private $contactId;

    private $name;

    private $email;

    public function __construct($contactId, $name, $email) {
        $this->contactId = $contactId;
        $this->name = $name;
        $this->email = $email;
    }

    public function setContactId($contactId) {
        $this->contactId = $contactId;

        return $this;
    }

    public function getContactId() {
        return $this->contactId;
    }

    public function setName($name) {
        $this->name = $name;

        return $this;
    }

    public function getName() {
        return $this->name;
    }

    public function setEmail($email) {
        $this->email = $email;

        return $this;
    }

    public function getEmail() {
        return $this->email;
    }
}

$contacts = [];

$contacts[] = new Contact(1, "contact 1", "contact1@test.com");
$contacts[] = new Contact(2, "contact 2", "contact2@test.com");
$contacts[] = new Contact(3, "contact 3", "contact3@test.com");

I have used collect(array) function on $contacts to convert to the collection and used where condition to find the object.我在 $contacts 上使用 collect(array) function 转换为集合,并使用 where 条件来查找 object。 but it returned null.但它返回了 null。

  $contact = $contacts->where('contactId', 1)->first()

I found that upon changing the contactId property to "public" access I got the object from my query.我发现在将 contactId 属性更改为“公共”访问权限后,我从查询中得到了 object。

Contact {#347
  +contactId: 1
  -name: "contact 1"
  -email: "contact1@test.com"
}

I am still confused why collection cannot access the private attribute, it should access it through getter of the attribute.我仍然很困惑为什么集合不能访问私有属性,它应该通过属性的 getter 访问它。 If I am changing the attributes access, the possibly i am going against encapsulation.如果我要更改属性访问,我可能会反对封装。

The whole point of private attribute is that nobody can access it outside class.私有属性的全部意义在于没有人可以在 class 之外访问它。 So only public can be accessed from outside.所以只有 public 可以从外部访问。

As you are using laravel collection you can use filter and provide condition on the getter function.当您使用 laravel 集合时,您可以使用过滤器并在吸气剂 function 上提供条件。

collect($contacts)->filter(function ($q){
            return $q->getContactId()==1;
        });

Or if you want only the first then或者如果你只想要第一个

collect($contacts)->filter(function ($q){
            return $q->getContactId()==1;
        })->first();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM