简体   繁体   中英

API Platform - Subresources: Cannot use reference for lookup or graphLookup: dbRef references are not supported (MongoDB-Symfony6.2)

I am currently working on programming a website using Symfony version 6.2 and API Platform in addition to MongoDB (version v6.0.3) in the database.

I try to use the Subresources and I followed the official documentation of the API Platform: https://api-platform.com/docs/core/subresources/

I tried to use exactly what is written on the documentation (this the code):

#[ApiResource(
    uriTemplate: '/companies/{companyId}/employees',
    operations: [ new GetCollection() ]
    uriVariables: [
        'companyId' => new Link(toProperty: 'company', fromClass: Company::class),
    ]
)]
class Employee
{
    #[MongoDB\Id()]
    private string $id;

    #[MongoDB\Field(type: Type::STRING)]
    private string $name;

    #[MongoDB\ReferenceOne(targetDocument: Company::class, inversedBy: "employees")]
    private ?Company $company;

    public function getId()
    {
        return $this->id;
    }
}

and for the Company class:

#[ApiResource]
class Company
{
    #[MongoDB\Id()]
    public string $id;

    #[MongoDB\Field(type: Type::STRING)]
    public string $name;

    #[MongoDB\ReferenceMany(targetDocument: Employee::class, mappedBy: "company")]
    /** @var Employee[] */
    #[Link(toProperty: 'company')]
    public $employees = [];
}

but while using the Postman to get the result from /companies/{companyId}/employees , this error message appears:

"Cannot use reference 'company' in class 'App\\Document\\Company' for lookup or graphLookup: dbRef references are not supported."

Is there any solution for that?

Use storeAs: 'id' in the relation reference

#[ApiResource(
    uriTemplate: '/companies/{companyId}/employees',
    operations: [ new GetCollection() ]
    uriVariables: [
        'companyId' => new Link(toProperty: 'company', fromClass: Company::class),
    ]
)]
class Employee
{
    #[MongoDB\Id()]
    private string $id;

    #[MongoDB\Field(type: Type::STRING)]
    private string $name;

    #[MongoDB\ReferenceOne(storeAs: 'id', targetDocument: Company::class, inversedBy: "employees")]
    private ?Company $company;

    public function getId()
    {
        return $this->id;
    }
}

And the Company class:

#[ApiResource]
class Company
{
    #[MongoDB\Id()]
    public string $id;

    #[MongoDB\Field(type: Type::STRING)]
    public string $name;

    #[MongoDB\ReferenceMany(storeAs: 'id', targetDocument: Employee::class, mappedBy: "company")]
    /** @var Employee[] */
    #[Link(toProperty: 'company')]
    public $employees = [];
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM