HasMany and BelongsTo relations don't work [Ru] #334
-
No duplicates 🥲.
What happened?В бд есть 3 таблицы: projects, users и files. [
'user' => [
SchemaInterface::ENTITY => User::class,
SchemaInterface::MAPPER => Mapper::class,
SchemaInterface::REPOSITORY => UserRepository::class,
SchemaInterface::TYPECAST_HANDLER => TypecastHandler::class,
SchemaInterface::DATABASE => 'default',
SchemaInterface::TABLE => 'users',
SchemaInterface::PRIMARY_KEY => 'id',
SchemaInterface::COLUMNS => [
// property => column
'id', 'email', 'firstName' => 'first_name', 'lastName' => 'last_name',
'hash' => 'password_hash', 'phone', 'createdAt' => 'created_at',
'updatedAt' => 'updated_at', 'roleId' => 'role_id', 'companyName' => 'company_name',
'jobName' => 'job_name', 'aboutMe' => 'about_me', 'banned', 'links',
'personVerified' => 'person_verified', 'emailVerified' => 'email_verified'
],
SchemaInterface::TYPECAST => [
'id' => 'int',
'email' => 'email',
'phone' => 'phone',
'hash' => 'hash',
'banned' => 'bool',
'emailVerified' => 'bool',
'personVerified' => 'bool',
'links' => 'links',
'createdAt' => 'carbon',
'updatedAt' => 'carbon',
],
SchemaInterface::RELATIONS => [
'role' => [
Relation::TYPE => Relation::BELONGS_TO,
Relation::TARGET => 'role',
Relation::SCHEMA => [
Relation::CASCADE => true,
Relation::INNER_KEY => 'roleId',
Relation::OUTER_KEY => 'id',
],
],
'files' => [
Relation::TYPE => Relation::HAS_MANY,
Relation::TARGET => 'file',
Relation::SCHEMA => [
Relation::CASCADE => true,
Relation::INNER_KEY => 'id',
Relation::WHERE => ['destination' => FileType::avatar->name],
Relation::OUTER_KEY => 'uploaderId'
],
],
]
],
'file' => [
SchemaInterface::ENTITY => File::class,
SchemaInterface::MAPPER => Mapper::class,
SchemaInterface::REPOSITORY => FileRepository::class,
SchemaInterface::TYPECAST_HANDLER => TypecastHandler::class,
SchemaInterface::DATABASE => 'default',
SchemaInterface::TABLE => 'files',
SchemaInterface::PRIMARY_KEY => 'id',
SchemaInterface::COLUMNS => [
// property => column
'id', 'uri', 'filename', 'size',
'projectId' => 'project_id', 'destination', 'metadata',
'uploadedAt' => 'uploaded_at', 'uploaderId' => 'uploader_id'
],
SchemaInterface::TYPECAST => [
'uploaderId' => 'int',
'projectId' => 'int',
'metadata' => 'array'
],
SchemaInterface::RELATIONS => [
'project' => [
Relation::TYPE => Relation::BELONGS_TO,
Relation::TARGET => 'project',
Relation::SCHEMA => [
Relation::CASCADE => true,
Relation::INNER_KEY => 'projectId',
Relation::OUTER_KEY => 'id',
Relation::NULLABLE => true,
],
],
'uploader' => [
Relation::TYPE => Relation::BELONGS_TO,
Relation::TARGET => 'user',
Relation::SCHEMA => [
Relation::CASCADE => true,
Relation::INNER_KEY => 'uploaderId',
Relation::OUTER_KEY => 'id',
],
]
]
],
'project' => [
SchemaInterface::ENTITY => Project::class,
SchemaInterface::MAPPER => Mapper::class,
SchemaInterface::REPOSITORY => ProjectRepository::class,
SchemaInterface::TYPECAST_HANDLER => TypecastHandler::class,
SchemaInterface::DATABASE => 'default',
SchemaInterface::TABLE => 'projects',
SchemaInterface::PRIMARY_KEY => 'id',
SchemaInterface::COLUMNS => [
// property => column
'id', 'title', 'slug', 'views', 'published',
'photographerId' => 'photographer_id', 'body',
'createdAt' => 'created_at', 'updatedAt' => 'updated_at',
'categoryId' => 'category_id', 'publishedAt' => 'published_at',
],
SchemaInterface::TYPECAST => [
'id' => 'int',
'views' => 'int',
'published' => 'bool',
'createdAt' => 'carbon',
'updatedAt' => 'carbon',
'publishedAt' => 'carbon'
],
SchemaInterface::RELATIONS => [
'photos' => [
Relation::TYPE => Relation::HAS_MANY,
Relation::TARGET => File::class,
Relation::SCHEMA => [
Relation::CASCADE => true,
Relation::INNER_KEY => 'id',
Relation::OUTER_KEY => 'projectId'
],
],
'photographer' => [
Relation::TYPE => Relation::BELONGS_TO,
Relation::TARGET => 'user',
Relation::SCHEMA => [
Relation::CASCADE => true,
Relation::INNER_KEY => 'photographerId',
Relation::OUTER_KEY => 'id',
],
],
'category' => [
Relation::TYPE => Relation::BELONGS_TO,
Relation::TARGET => 'category',
Relation::SCHEMA => [
Relation::CASCADE => true,
Relation::INNER_KEY => 'categoryId',
Relation::OUTER_KEY => 'id',
Relation::NULLABLE => true
],
]
]
],
] При попытке сохранить пользователя с аватаром крашится транзакция ссылаясь на невозможность заресолвить новый файл в свзязи projects.photos.file. Transaction can't be finished. Some relations can't be resolved: Create new `file` - project.photos:file (Cycle\ORM\Relation\ShadowBelongsTo) При том, что project или projecId у сохраняемого файла с аватаркой является пустым, сама сущность проекта не инициализируется. VersionORM 2.0.1
PHP 8.1 |
Beta Was this translation helpful? Give feedback.
Replies: 4 comments
-
The relation 'file' => [
// ...
SchemaInterface::RELATIONS => [
'project' => [
// ...
Relation::SCHEMA => [
Relation::INNER_KEY => 'id',
Relation::OUTER_KEY => 'projectId', They should be swapped: Relation::INNER_KEY => 'projectId',
Relation::OUTER_KEY => 'id', |
Beta Was this translation helpful? Give feedback.
-
Изначально оно так и было, я пытался поменять ключи и по ошибке выгрузил эту схему. Проблема сохраняется и при правильной постановке ключей и при текущей. |
Beta Was this translation helpful? Give feedback.
-
Если на одной стороне связи выставлено NULLABLE = true, то и на другой стороне должно быть тоже самое. |
Beta Was this translation helpful? Give feedback.
-
Если на одной стороне связи выставлено NULLABLE = true, то и на другой стороне должно быть тоже самое. |
Beta Was this translation helpful? Give feedback.
Если на одной стороне связи выставлено NULLABLE = true, то и на другой стороне должно быть тоже самое.
Т.е. если у file.project nullable = true, то и у project.photos нужно nullable=true.
Возможно projectId не выставлялся из-за того, что были перепутаны inner/outer keys?
Предлагаю привести схему к полному соответствию и попробовать ещё раз