我有一个用户和一个学校实体。这两个实体都有很多关系。
class User
{
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORM\ManyToMany(targetEntity="AppBundle\Entity\School")
* @ORM\JoinTable(name="user_school",
* joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")},
* inverseJoinColumns={@ORM\JoinColumn(name="school_id", referencedColumnName="id")}
* )
*/
private $school;
public function __construct()
{
$this->school = new ArrayCollection();
}
}
class School
{
/**
* @ORM\Column(type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
public function getId()
{
return $this->id;
}
}
如果我在我的控制器中调用了重新获取学校ID的方法,如:
public function indexAction(Request $request)
{
$user = $this->getUser();
$school = $user->getSchool();
echo $school->getId();
}
我收到错误消息
Attempted to call an undefined method named "getId" of class "Doctrine\ORM\PersistentCollection"
有人能给我提示,我做错了吗?
答案 0 :(得分:2)
即使$user->getSchool();
在方法名称中是单数,它也会返回PersistentCollection
- 学校的集合(因为关系为ManyToMany
)。如果你想得到一个特定学校的id,你就必须遍历学校,如下:
$scools = $user->getSchool()->toArray();
foreach ($scools as $scool) {
// do something with $school
}
答案 1 :(得分:0)
在您定义的映射中,User::$school
是ManyToMany
,这意味着getSchool
的结果将是Collection
Schools
,而不是School
$school
实体。
两种情况:
用户可以拥有多个学校。然后,您可能应该将$schools
重命名为getSchool
,将getSchools
重命名为$user->getSchools()->getId()
。而且,由于$user->getSchools()
是Collection
并且没有getId
方法,因此您无法致电ManyToOne
。查看@ NoyGabay的答案,了解访问学校ID的方法。
用户只能拥有一所学校。然后你没有正确定义你的映射;你想要一个ManyToMany
而不是 NSData *allCoursesData = [[NSData alloc] initWithContentsOfURL:
[NSURL URLWithString:@"http://www.pumba.se/example.json"]];
NSError *error;
NSMutableDictionary *JSONdictionary = [NSJSONSerialization
JSONObjectWithData:allCoursesData
options:kNilOptions
error:&error];
if( error )
{
NSLog(@"%@", [error localizedDescription]);
}
else {
NSMutableArray *allNames = [NSMutableArray array];
NSArray* entries = [JSONdictionary valueForKeyPath:@"hits.hits"];
for (NSDictionary *hit in entries) {
NSArray *versions = hit[@"versions"];
for (NSDictionary *version in versions) {
NSDictionary *properties = version[@"properties"];
NSString *status = [properties[@"Status"] firstObject];
NSString *name = [properties[@"Name"] firstObject];
if ([status isEqualToString:@"usable"]) {
[allNames addObject:name];
}
}
}
NSLog(@"All names: %@", allNames);
}}
。查看Doctrine's documentation for association mapping。