在foreach循环中更新实体

时间:2019-02-10 22:08:44

标签: php symfony doctrine symfony4

我需要检查数据库中是否存在数组中的ID,是否需要在某一列中放置一些“标志”,但是我对此有问题。

$ch = curl_init();
    curl_setopt($ch, CURLOPT_URL,$url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER,1);
    curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);

    curl_setopt($ch, CURLOPT_USERPWD, "$login:$password");
    $fields = curl_exec($ch);

    $reader = Reader::createFromString($fields, 'r')
        ->setDelimiter(',');

    $records = $reader->getRecords(['id_pr']);

    foreach ($records as $offset => $record) {
        $product = $this->productsRepository->findOneBy(['id_pr' => $record['id_pr']]);

This is where i need to update my DB, for each record i need to update 
column 'flag' by eg. '1' but i dont know how :(

    }
    curl_close($ch);

我尝试了类似$ product-> setFlag(1)的方法;但是我无法打电话给二传手或二传手

它给我错误:在null上调用成员函数setFlag()

这是我的“产品”实体的外观:

class Products
{    

/**
 * @ORM\Column(type="integer")
 */
private $id_pr;
/**
 * @ORM\Column(type="integer", nullable=true)
 */
private $flag;

public function getIdPr(): ?int
{
    return $this->id_pr;
}

public function setIdPr(int $id_pr): self
{
    $this->id_pr = $id_pr;

    return $this;
}

/**
 * @return mixed
 */
public function getFlag()
{
    return $this->flag;
}

/**
 * @param mixed $flag
 */
public function setFlag($flag): void
{
    $this->flag = $flag;
}

1 个答案:

答案 0 :(得分:0)

foreach ($records as $offset => $record) {
    $product = $this->productsRepository->findOneBy(['id_pr' => $record['id_pr']]);
    if($product) {
        $product->setFlag($flagValue);
        $this->getDoctrine()->getManager()->flush(); //I'm assuming that you're in a controller
    }
}