symfony - Symfony - ArrayCollection - 更新或创建
问题描述
- Symfony 4.3
- 目标:导入包含教义的 CSV 列表员工/公司并将其保存到数据库中。
我有实体公司:
<?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 方法?
解决方案
与Employees
Doctrine 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();
推荐阅读
- python - 在 opencv-python cap.read() 1 秒后返回 false
- sql - 将数据类型从 varchar 更改为 integer
- javascript - 当对象中的字段发生更改时如何从 v-model 数组中删除对象
- mysql - 它有什么错误,很简单,错误显示在最后一个“结束”语句中。什么是错误
- java - LWJGL+XCB 随机崩溃
- android - recyclerView.scheduleLayoutAnimation() 是如何工作的?
- c# - 数据未从 Office 365 的 Outlook 中检索?
- php - 如何将二进制转换为base64?
- java - 签名的 jar 被 java 安全阻止运行
- rust - 加号的 Rust 宏重复