首页 > 解决方案 > Symfony - ArrayCollection - 更新或创建

问题描述

我有实体公司:

<?php

// src/Entity/Company.php
class Company
{

    /**
    * @ORM\OneToMany(targetEntity="App\Entity\Employee", mappedBy="company")
    */
    private $employees;

    public function __construct()
    {
        $this->employees = new ArrayCollection();
    }

    public function getEmployees()
    {
        return $this->employees;
    }

和 Employee 实体:

<?php

// src/Entity/Employee.php
class Employee
{

    /**
    * @ORM\ManyToOne(targetEntity="App\Entity\Company", inversedBy="employees")
    */
    private $company;

    public function getCompany()
    {
        return $this->company;
    }

    public function setCompany(?Company $company)
    {
        $this->company = $company;
        return $this;
    }

下面是导入的 CSV 每一行的循环:

<?php

    // $csv = array made from the CSV file
    // e.g. $csv[0]['employee_name'] = "John Doe"
    // e.g. $csv[0]['employee_mail'] = "john.doe@bmw.com"
    // e.g. $csv[0]['employee_company_name'] = "BMW"
    // e.g. $csv[0]['employee_company_id'] = 77

    foreach($csv as $key => $value)
    {
        if($company = $this->em->getRepository(Company::class)->find($value['employee_company_id']))
        {
            // if the employee doest not exist, create it
            // IN MY TESTS, HERE IS MY PROBLEM
            // DON'T KNOW HOW TO LOOP INSIDE THE EMPLOYEES LIST USING the MAIL
            if ($company->getEmployees()->contains($value['employee_mail']))
            {
                // This employee for this company exists, let's update it
            }
            else
            {
                // This employee for this company does not exist, let's create it
            }
        }
        else
        {
            // Create the company
        }

我不知道如何在公司员工列表中循环,以确定我是否必须编辑(员工已经存在)或创建新员工。也许我不应该使用 ArrayCollection::contains 方法?

标签: symfonydoctrine-ormdoctrine

解决方案


EmployeesDoctrine ArrayCollection 一样,您可以exists在其上使用该方法。此方法接受一个闭包作为参数,该闭包循环遍历集合中的所有元素并true在条件匹配时返回。

if ($company->getEmployees()->exists(function ($key, Employee $employee) use ($value) {
    return $employee->getEmail() === $value['employee_mail'];
})) {
    // Employee exists, update
} else {
    // Employee does not exist
}

或者,如果您想立即创建/更新记录,您可以执行以下操作。如果存在则返回,Employee如果不存在则创建一个新Employee对象

$employee = $company
    ->getEmployees()
    ->filter(function (Employee $employee) use ($value) {
        return $employee->getEmail() === $value['employee_mail'];
    })
    ->first() ?? new Employee();

推荐阅读