Remove all related children in Symfony entity ManyToOne - doctrine-orm

That is my relations:
in CategoryField Entity:
manyToOne:
category:
targetEntity: Category
inversedBy: fields
joinColumn:
name: category_id
referencedColumnName: id
in Category:
oneToMany:
fields:
orderBy: { 'name': 'ASC' }
targetEntity: CategoryField
mappedBy: category
cascade: ['remove']
I'm trying to remove all fields when I save category(before inserts new fields):
if (!$category = $categoryRepo->find($item_id)) {
$category = new Category();
} else {
$category->clearFields();
}
That is clear fields method in Category entity:
public function clearFields() {
$this->fields->clear();
}
Fields does not remove and new fields inserts in related table. That's makes duplicates.
How can I remove all related records(fields) with my association?

Related

GraphQL save self relation in custom resolver in amplify

I have the following models:
type Field #model {
id: ID!
fieldID: ID #index(name: "byField", sortKeyFields: ["name"])
name: String!
type: String!
required: Boolean
fields: [Field] #hasMany(indexName: "byField", fields: ["id"])
}
type Mutation {
batchCreateField(fields: [BatchCreateField]): [Field]
}
input BatchCreateField {
id: ID
fieldID: ID
name: String!
type: String!
required: Boolean
fields: [BatchCreateField]
}
And wrote a custom resolver:
$util.log.info($util.toJson($context))
#set($isAuthorized = false)
#set( $createdAt = $util.time.nowISO8601() )
#set($fieldsArray = [])
#foreach($item in \${ctx.args.fields})
$util.qr($item.put("id", $util.defaultIfNullOrBlank($item.id, $util.autoId())))
$util.qr($item.put("createdAt", $util.defaultIfNull($item.createdAt, $createdAt)))
$util.qr($item.put("updatedAt", $util.defaultIfNull($item.updatedAt, $createdAt)))
$util.qr($item.put("__typename", "Field"))
$util.qr($fieldsArray.add($util.dynamodb.toMapValues($item)))
#end
## [End] Initialization default values. **
$util.toJson( {
"version": "2018-05-29",
"operation": "BatchPutItem",
"tables": {
"Field-INSERT_APIID-INSERT_PROJECT_ENV": $fieldsArray
}
} )
Saving in batch works fine, the self relation is not working. Is there any way i can save this self relation like below in a batch and the resolver autofilling the sub fields with the fieldID of the previously inserted field?
let fieldInput: CreateFieldInput = {
name: field.name,
type: field.type,
required: field.required,
fields: field.fields
};
batchFieldsInput.push(fieldInput)
API.graphql(graphqlOperation(batchCreateField, {fields: batchFieldsInput}))

AWS Amplify GraphQL - One to Many connections return empty list when queried

I've been following the AWS GraphQL CLI guide for setting up an API for my app, but am having trouble with connections.
The following is my current Graphql schema, with some attributes removed
type Employee #model {
id: ID!
employment: [Employment!] #connection(name: "byEmployeeIDByCompanyID", fields: ["id"])
}
type Company #model {
id: ID!
employees: [Employment!] #connection(name: "byCompanyIDByDateHired", fields: ["id"])
}
type Employment #model
#key(name: "byEmployeeIDByCompanyID", fields: ["employeeID", "companyID"], queryField: "employmentByEmployeeIDByCompanyID") {
id: ID!
companyID: ID!
employeeID: ID!
company: Company! #connection(fields: ["companyID"])
employee: Employee! #connection(fields: ["employeeID"])
}
When I query Employees or Companys, [Employment] always returns an empty array. Do I need to edit the resolvers for these fields? They should work out of the box, no?
From my understanding, using #key with 'name' and multiple 'fields' creates a secondary index on the table, and specifying that key with #connection tells the connection to use that key instead of the tables primary index. In the "byEmployeeIDByCompanyID" key, for example, employeeID is the partition key, and companyID is the sort key. A query on the "employmentByEmployeeIDByCompanyID" queryField with an employeeID but no companyID returns all the employments for a given employee, which is what I want, so why isn't the connection working?
I found success in editing the resolvers, so I'm going to go with this for now. For Employee.employment, I added:
"index": "byEmployeeIDByCompanyID",
to the request mapping template, and changed the query from:
{
"expression": "#partitionKey = :partitionKey",
"expressionNames": {
"#partitionKey": "id"
},
"expressionValues": {
":partitionKey": {
"S": "$context.source.id"
}
}
}
to
{
"expression": "#partitionKey = :partitionKey",
"expressionNames": {
"#partitionKey": "employeeID"
},
"expressionValues": {
":partitionKey": {
"S": "$context.source.id"
}
}
}

Error: GraphQL error: Query condition missed key schema element

I am using Amplify and therefore DynamoDB. I believe I have a fairly simple schema setup, but coming from MySQL my brain is going a little screw!!
The basic setup (a football league) is,
[League]
[Season]
[Divisions]
[Teams]
[Club]
[Ground]
[Club]
[Teams]
[TeamConnection] (I needed a connection schema as a team can belong to multiple divisions/seasons/leagues. I could not think of another way to connect this on the `Team` model)
[League]
[Season]
[Division]
Schemas
....
Other Schemas
...
type Club #model #key(name: "byClub", fields: ["leagueID", "name"])
{
id: ID!
name: String!
leagueID: ID!
leagues: [League] #connection(fields: ["leagueID"])
teams: [Team] #connection(keyName: "byTeams", fields: ["id"])
grounds: [Ground] #connection(keyName: "byGround", fields: ["id"])
}
enum TeamGender {
Male
Female
}
type Team #model
#key(name: "byTeamsClubId", fields: ["clubID"])
#key(name: "byTeams", fields: ["clubID", "name"])
{
id: ID!
name: String!
faId: ID!
clubID: ID!
club: Club #connection(fields: ["clubID"])
teamDetails: [TeamConnection] #connection(keyName: "byTeamsConnection", fields: ["id"])
gender: TeamGender!
}
type TeamConnection #model #key(name: "byTeamsConnection", fields: ["teamID","seasonID", "leagueID", "divisionID"])
{
id: ID!
teamID: ID!
leagueID: ID!
seasonID: ID!
divisionID: ID!
leagues: [League] #connection(fields: ["leagueID"])
teams: [Team] #connection(fields: ["teamID"])
seasons: [Season] #connection(fields: ["seasonID"])
divisions: [Division] #connection(fields: ["divisionID"])
}
type Ground #model #key(name: "byGround", fields: ["clubID", "name"])
{
id: ID!
name: String!
address1: String
address2: String
town: String
postcode: String
rating: Int
type: String
link: String
clubID: ID!
clubs: [Club] #connection(fields: ["clubID"])
}
Error
This query works with no error
//$leagueID: ''
export const LIST_CLUBS = /* GraphQL */ `
query ListClubs($leagueID: ID) {
listClubs(filter: { leagueID: { eq: $leagueID } }) {
items {
name
leagueID
}
}
}
`
This is the auto generated query used. If I used the below query, then the error seen below will kick in. This does confuse me.
//filter: { leagueID: { eq: leagueID } },
export const listClubs = /* GraphQL */ `
query ListClubs(
$filter: ModelClubFilterInput
$limit: Int
$nextToken: String
) {
listClubs(filter: $filter, limit: $limit, nextToken: $nextToken) {
items {
id
name
leagueID
leagues {
items {
id
name
faId
logo
seasons {
items {
id
name
faId
yearStart
yearEnd
leagueID
createdAt
updatedAt
}
nextToken
}
division {
items {
id
name
faId
divisionSeasonFaId
leagueID
seasonID
ageInput
level
createdAt
updatedAt
}
nextToken
}
createdAt
updatedAt
}
nextToken
}
teams {
items {
id
name
faId
clubID
club {
id
name
leagueID
leagues {
nextToken
}
teams {
nextToken
}
grounds {
nextToken
}
createdAt
updatedAt
}
teamDetails {
items {
id
teamID
leagueID
seasonID
divisionID
createdAt
updatedAt
}
nextToken
}
gender
createdAt
updatedAt
}
nextToken
}
grounds {
items {
id
name
address1
address2
town
postcode
rating
type
link
clubID
clubs {
items {
id
name
leagueID
createdAt
updatedAt
}
nextToken
}
createdAt
updatedAt
}
nextToken
}
createdAt
updatedAt
}
nextToken
}
}
`;
//Console
Error: GraphQL error: Query condition missed key schema element
GraphQL error: Query condition missed key schema element
GraphQL error: Query condition missed key schema element
GraphQL error: Query condition missed key schema element
GraphQL error: Query condition missed key schema element
GraphQL error: Query condition missed key schema element
GraphQL error: Query condition missed key schema element
GraphQL error: Query condition missed key schema element
GraphQL error: Query condition missed key schema element
GraphQL error: Query condition missed key schema element
GraphQL error: Query condition missed key schema element
at new ApolloError (/var/www/co.uk/node_modules/apollo-client/bundle.umd.js:92:26)
Query working as mentioned above.
Errors returned from GraphIQL
However frustratingly, which I did not know. The data is actually returned, plus the errors at the end.

sequelize multiple primary keys

I have some problem with Sequelize having multiple primary keys; therefore the multiple foreign keys with multiple hasMany on same table.
Suppose I have User
const User = sequelize.define('User', {
id: { type: DataTypes.STRING(6), field: 'ID', primaryKey : true }
)
associate: function(models) {
User.hasMany(models.Post, { foreignKey: 'userId' });
}
and I have Post under User
const Post = sequelize.define('Post', {
id: { type: DataTypes.STRING(6), field: 'ID', primaryKey: true }, // primary key
userId: { type: DataTypes.STRING(6), field: 'USER_ID', primaryKey: true }, // primary key
)
associate: (models) => {
Post.belongsTo(models.User, { foreignKey: 'userId' });
Post.hasMany(models.PostImage, { onDelete: 'CASCADE', foreignKey: 'postId' });// { key1: 'id', key2: 'userId'}
Post.hasMany(models.PostImage, { onDelete: 'CASCADE', foreignKey: 'userId' });// { key1: 'id', key2: 'userId'}
}
and Post Images under Post
const PostImage = sequelize.define('PostImage', {
postId: { type: DataTypes.STRING(6), field: 'POST_ID', primaryKey: true },
userId: { type: DataTypes.STRING(6), field: 'USER_ID', primaryKey: true }
)
associate: (models) => {
PostImage.belongsTo(models.Post, { foreignKey: 'postId' });
PostImage.belongsTo(models.Post, { foreignKey: 'userId' });
}
Now it seems like two primary keys with two foreign keys are not working for 'include' method for using findOne or findAll.
Post.findAll({
attributes: ['id', 'userId', 'content', 'modifyDate', 'registerDate'],
where: {...},
include: [{
model: models.PostImages,
}
)
It seems only one primary key with one foreign key is linked to each other for table Post and Post Image. So If I remove the relation
Post.hasMany(models.PostImage, { onDelete: 'CASCADE', foreignKey: 'userId' });// { key1: 'id', key2: 'userId'}
from Post to make only one foreign key with Post Image, then it would work as I expected. But it causes the problem because it only considers Post ID of Post Image, not users, so that it brings the other user's post images as well.
How can I use the multiple primary keys with multiple foreign keys in sequelize?

Emberjs Model Associations. Calling a model that hasMany of another model

I have defined two models that each have a Many-to-Many relationship. I want to show a certain amount of 'people' to be a part a 'department'. How would I insert more people into a department? When I try to insert a 'person' into a 'department', the 'department' does not recognize the person's name as being a part of the 'person' model.
I've stated the relationship in the model
VpcYeoman.Department = DS.Model.extend({
departmentName: DS.attr('string'),
departmentMembers: DS.hasMany('person')
});
&
VpcYeoman.Person = DS.Model.extend({
profileName: DS.attr('string'),
profileDepartment: DS.hasMany('department')
});
And the controllers
VpcYeoman.PeopleController = Ember.ObjectController.extend({
actions: {
createPerson: function () {
// Get the todo title set by the "New Todo" text field
var profileName = this.get('profileName');
if (!profileName.trim()) { return; }
// Create the new Todo model
var person = this.store.createRecord('person', {
profileName: profileName,
isCompleted: false
});
// Clear the "New Todo" text field
this.set('profileName', '');
// Save the new model
todo.save();
}
}
});
VpcYeoman.DepartmentsController = Ember.ArrayController.extend({});
I won't post the HTML (.hbs) templates because they are incorrect.
var person = this.store.createRecord('person', {
profileName: 'joe shmo'
});
var dept = this.store.createRecord('department', {
departmentName: 'admin'
});
dept.get('departmentMembers').pushObject(person);
person.get('profileDepartment').pushObject(dept);