首页 > 解决方案 > 根据值在 Symfony 中设置多个实体

问题描述

我正在尝试根据值是否存在来设置多个实体。

if ($guestMinorCheckout === 'Yes') {
    $optionInfo = 'adult-authorized';
    $value = 'yes|';
    foreach ($guestMinorCheckout as $guestInfo) {
        if (!is_null($guestContactCheckInOutPhone)) {
            $option = new EventAttendeeOption();
            $option->setOption('adult-authorized-sms');
            $option->setValue($guestContactCheckInOutPhone);

        }
        if (!is_null($guestContactCheckInOutEmail)) {
            $option = new EventAttendeeOption();
            $option->setOption('adult-authorized-email');
            $option->setValue($guestContactCheckInOutEmail);
        }
    }
}

上面的这段代码不起作用,但它是我想要完成的。

我从 API 调用中获取这些数据,因此这些值可能存在也可能不存在。如果他们确实退出 id 喜欢设置为这些值。

标签: phpsymfonyforeachdoctrine-orm

解决方案


不确定你在哪里得到$guestContactCheckInOutPhone$guestContactCheckInOutPhone。我假设它们位于您所说的从 API 获得的某个数据数组中。希望它是一个键,键的值数组与字段名称相同。如果是这种情况,您可以使用反射类,而不是检查每个字段是否在数组中:

$option = new EventAttendeeOption();
$reflectionClass = new \ReflectionClass(EventAttendeeOption::class);

foreach ($data as $key => $value) {
    $reflectionClass->getProperty($key)->setValue($option, $value);
}

编辑:仔细检查后,我发现除了一些小的工作流程问题之外,您的代码应该可以工作,而我的答案并不完全符合您的需要。你能分享为什么它不起作用吗?


推荐阅读