我有两个表'User'和'Address',它们之间有一个OneToOne关系,因为User表有一个'address_id'列,它存储了Address表的'id'。
以下是用户实体中的注释:
/**
* @ORM\OneToOne(targetEntity="App\Entity\address", cascade={"persist", "remove"})
* @ORM\JoinColumn(nullable=false)
*/
private $address;
Security.yaml:
security:
encoders:
App\Entity\User:
algorithm: bcrypt
providers:
my_provider:
entity:
class: App\Entity\User
property: username
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
main:
anonymous: true
form_login:
login_path: login
check_path: login
provider: my_provider
default_target_path: dashboard
logout:
path: /logout
target: /
access_control:
- { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/dashboard, roles: ROLE_USER }
控制器:
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;
class SecurityController extends AbstractController
{
/**
* @Route("/login", name="login")
*/
public function login(Request $request,AuthenticationUtils $utils)
{
// get the login error if there is one
$error = $utils->getLastAuthenticationError();
// dump($error);die;
// last username entered by the user
$lastUsername = $utils->getLastUsername();
return $this->render('security/login.html.twig', [
'last_username' => $lastUsername,
'error' => $error
]);
}
public function logout()
{
# code...
}
}
我插入用户名和密码时收到此错误:
由于系统问题,无法处理身份验证请求。
这是我在控制器中转储()错误时得到的结果。
SecurityController.php on line 20: AuthenticationServiceException {#189 ▼ -token: UsernamePasswordToken {#236 ▶} #message: "The target-entity App\Entity\address cannot be found in 'App\Entity\User#address'." #code: 0 #file: "/home/users/kumar.saurabh/www/html/symfony/test-project/vendor/symfony/security-core/Authentication/Provider/DaoAuthenticationProvider.php" #line: 85 trace: {▶} }
当我删除$ address变量及其getter和setter函数时,登录工作正常,但是当我使用它时它会给我上面提到的错误。
如何使用外键实现此目的?我是symfony的新手,我正在学习4.2版本。
注意这种情况,用App \ Entity \ Address替换App \ Entity \ address,更新你的架构,应该没问题
/**
* @ORM\OneToOne(targetEntity="App\Entity\address", cascade={"persist", "remove"})
* @ORM\JoinColumn(nullable=false)
*/
private $address;
应该
/**
* @ORM\OneToOne(targetEntity="App\Entity\Address", cascade={"persist", "remove"})
* @ORM\JoinColumn(nullable=false)
*/
private $address;