Symfony 4选民-一对多关系

时间:2019-10-03 06:05:33

标签: symfony doctrine-orm

我有一个Application实体,该实体存储带有用户ID的广告ID

class User implements UserInterface, \Serializable
{
 /**
 * @ORM\OneToMany(targetEntity="App\Entity\Application", mappedBy="author", orphanRemoval=true)
 */
 private $applications;
 }

应用程序实体

class Application
{

/**
 * @ORM\ManyToOne(targetEntity="App\Entity\Advert", inversedBy="applications")
 * @ORM\JoinColumn(nullable=false)
 */
private $advert;

/**
 * @ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="applications")
 * @ORM\JoinColumn(nullable=false)
 */
private $author;
}

我想要的是当当前用户已经申请特定广告时(观看广告时)可以拒绝采取行动的选民 至今 在选民中争夺

class AdvertApplicationsVoter扩展了Voter {

protected function supports($attribute, $subject)
{
    return in_array($attribute, ['APP_APPLY', 'ADVERT_APPLY'])  && $subject instanceof Application;
}

/**
 * @param string $attribute
 * @param mixed $subject
 * @param TokenInterface $token
 * @return bool
 */
protected function voteOnAttribute($attribute, $subject, TokenInterface $token)
{
    $user = $token->getUser();
    $apl = $user->getApplications();
    // if the user is anonymous, do not grant access
    if (!$user instanceof User) {
        return false;
    }

    switch ($attribute) {
        case 'APP_APPLY':
            return $this->dw($user, $subject);
            break;
        case 'ADVERT_APPLY':
            // logic to determine if the user can VIEW
            // return true or false
            break;
    }

    return false;
}

private function applied(?User $user, Advert $app)
{
    return $user->getId() === $app->getApplications()->getKeys();
}
private function aa(?User $user, Application $app)
{
    return $user->getApplications() === $app->getAdvert();
}

private function dw(?User $user, Application $app)
{
    foreach($user->getApplications() as $app) {
        if ($app->getAdvert() === $app) {
            return false;
        }
    }
    return true;
 }
}

我的访问权限被弃权,我不知道如何调试选民

预先感谢

1 个答案:

答案 0 :(得分:1)

假设您正确设置了选民(因此使用 supports voteOnAttribute 方法)。

然后您只需要更改方法:

private function dw(?User $user, Advert $advert)
{
    foreach($user->getApplications() as $userApplication) {
        if ($userApplication->getAdvert() === $advert) {
            return false;
        }
    }
    return true;
 }
}

您的方法存在的问题是,您正在将 ArrayCollection 应用程序对象进行比较。