I'm trying to get some tables:
The migration was:
migrationBuilder.CreateTable(
name: "Products",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Name = table.Column<string>(type: "nvarchar(max)", nullable: true),
Description = table.Column<string>(type: "nvarchar(max)", nullable: true),
Version = table.Column<string>(type: "nvarchar(max)", nullable: true),
ReleaseDate = table.Column<DateTime>(type: "datetime2", nullable: false),
IsReleased = table.Column<bool>(type: "bit", nullable: false),
IsActive = table.Column<bool>(type: "bit", nullable: false),
IsDeleted = table.Column<bool>(type: "bit", nullable: false),
Created = table.Column<DateTime>(type: "datetime2", nullable: false),
Modified = table.Column<DateTime>(type: "datetime2", nullable: false),
RowVersion = table.Column<byte[]>(type: "rowversion", rowVersion: true, nullable: true),
TestText = table.Column<string>(type: "nvarchar(50)", maxLength: 50, nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Products", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Licenses",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
Licensenumber = table.Column<string>(type: "varchar(50)", maxLength: 50, nullable: false),
ProductId = table.Column<int>(type: "int", nullable: false),
UserId = table.Column<int>(type: "int", nullable: false),
Created = table.Column<DateTime>(type: "datetime2", nullable: false),
Modified = table.Column<DateTime>(type: "datetime2", nullable: false),
RowVersion = table.Column<byte[]>(type: "rowversion", rowVersion: true, nullable: true),
TestText = table.Column<string>(type: "nvarchar(50)", maxLength: 50, nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_Licenses", x => x.Id);
table.ForeignKey(
name: "FK_Licenses_Products_ProductId",
column: x => x.ProductId,
principalTable: "Products",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
table.ForeignKey(
name: "FK_Licenses_Users_UserId",
column: x => x.UserId,
principalTable: "Users",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
Now i'm getting while database creation: MERGE statement conflicted with the FOREIGN KEY constraint "FK_Licenses_Products_ProductId". The conflict occurred in database "app-licenseserver", table "dbo.Products", column 'Id'.
But what happend? Can i fix it?
It means there is no row in the Products table that matches the Id of the row of the entry you're trying to insert (merge).
Through your comments, it looks like you discovered a problem that left your products table empty but I wanted to add this:
Note: in your model the ProductId foreign key is not nullable, therefore if you don't set it, it will default to 0 and if that Id does not exist, you will also get this error.
This particular issue is what brought me to your question.
Related
i am writing in typescript,
i am trying this in member model:
mail: {
type: String,
unique: true,
nullable: true,
default: null,
}
Is it possible to reference composite primary keys in Sequelize?
I'm working on a web-app that helps organize kitchen waste. The restaurant organizes its weeks and months into 'periods' where the first week of September would be '9.1'. For every period, I need to create a new batch of ingredient objects that can keep track of what their prices and quantities were for that period. I figure it would be best to make the period primary keys their combined month and week, as that will be unique in the database.
I may add year on later, but that doesn't change my problem.
The database I'm working with is Postgres.
This is my period table model in my sequelize seed file:
.then(() => queryInterface.createTable('periods', {
month: {
type: Sequelize.INTEGER,
validate: {
max: 12,
min: 1
},
unique: "monthWeekConstraint",
primaryKey: true
},
week: {
type: Sequelize.INTEGER,
validate: {
max: 4,
min: 1
},
unique: "monthWeekConstraint",
primaryKey: true
},
createdAt: {
type: Sequelize.DATE
},
updtedAt: {
type: Sequelize.DATE
}
}))
I'd like to reference the periods stored in the above table in my periodItems table, which I have (incorrectly) looking like:
.then(() => queryInterface.createTable('periodItems', {
periodMonth: {
type: Sequelize.INTEGER,
references: {model: 'periods', key: 'monthWeekConstraint'}
},
periodWeek: {
type: Sequelize.INTEGER,
references: {model: 'periods', key: 'monthWeekConstraint'}
},
day: {
type: Sequelize.INTEGER,
validate: {
min: 1,
max: 7
}
},
...other irrelevant fields...
}))
I'm definitely new to databases, so I apologize if I'm way off. I've gotten a few other tables doing what I'd like, but I've been stuck on this problem for a few days.
While it is possible to create composite primary keys in Sequelize by specifying primaryKey: true against more than one column (as you have already done above), Sequelize doesn't currently support composite foreign keys, so there is no way to reference a model/table which has composite primary keys.
See https://github.com/sequelize/sequelize/issues/311 for a discussion on the subject.
model/product.js:
const Product = sequelize.define("product", {
sku: { type: Sequelize.STRING, allowNull: false, primaryKey: true },
title: { type: Sequelize.STRING, allowNull: false },
availability: {
type: Sequelize.STRING,
allowNull: false,
defaultValue: false,
}
});
model/Attribute.js:
const Attribute = sequelize.define("attribute", {
key: { type: Sequelize.STRING, allowNull: false, primaryKey: true },
productSku: { type: Sequelize.STRING, allowNull: false, primaryKey: true },
value: { type: Sequelize.STRING, allowNull: false },
});
After importing to app.js:
product.hasMany(attribute, { foreignKey: "productSku", sourceKey: "sku" });
attribute.belongsTo(product, { foreignKey: "productSku", targetKey: "sku" });
Explanation:
Product.sku is exported as foreign key to Attibute.productSku. Attribute table has a composite foreign (key + productSku), and a ForeignKey(productSku) from product.sku;
I'm working with an existing dataBase (from my company) and they want to build an intranet with symfony 4.
I created my doctrine files and the doctrine database.
And after that i used some insert command for work with all the data from the existing dataBase in the doctrine database and in my symfony project.
For the moment everything work very well !
But I want to add a relationship mapping (one-to-many, many-to-one, many-to-many) in my doctrine model now.
And in all the exemple that i found they link the model with each other inside fixture or with some new data to insert in dataBase
So I added a One-To-One unidirectionnal relationship in my Bodyshops.orm.yml link to the BodyshopsEmail.orm.yml and after used the
doctrine:schema:update --force
With success, I want to use my Bodyshops Model in a Controller and I got a
Missing value for primary key senderEmail on App\Entity\BodyshopsEmail
I know that the question was put
Missing value for primary key id Doctrine Symfony2
Doctrine - "Missing value for primary key"
But I guess that the error is here because I got two ID in my bodyshopsEmail id(same as bodyshops.id) and senderMail(Set foreach row in bodyshopsEmail)
I want to know if i have to make a script that will bind my actual data relationship mapping for avoid the error or if the error doesn't come from the linking but from the orm.yml for exemple
Hope that I am clear enough , thank's for reading :p my files are below
(EN)
http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/association-mapping.html
(FR)
https://www.jdecool.fr/blog/2017/09/20/tutorial-jobeet-symfony-4-partie-3a-le-modele-de-donnees.html
https://openclassrooms.com/courses/developpez-votre-site-web-avec-le-framework-symfony2/les-relations-entre-entites-avec-doctrine2#=
Bodyshops.orm.yml
App\Entity\Bodyshops:
type: entity
id:
id: #B
type: string
length: 2
fields:
accessFrom:
type: string
length: 5
nullable: false
region:
type: string
length: 8
nullable: false
name:
type: string
length: 32
nullable: false
nameAlternative:
type: string
length: 32
nullable: false
nameCode:
type: string
length: 32
nullable: false
phone:
type: string
length: 16
nullable: true
fax:
type: string
length: 16
nullable: true
website:
type: string
length: 64
nullable: true
address1:
type: string
length: 64
nullable: false
address2:
type: string
length: 64
nullable: true
address3:
type: string
length: 64
nullable: true
zip:
type: string
length: 6
nullable: false
city:
type: string
length: 32
nullable: false
country:
type: string
length: 32
nullable: false
countryCode:
type: string
length: 4
nullable: false
colorBackground:
type: string
length: 8
nullable: false
colorText:
type: string
length: 8
nullable: true
workshopSlots:
type: integer
length: 4
nullable: false
departements:
type: string
length: 32
nullable: false
ipList:
type: json_array
nullable: true
identRepa:
type: string
length: 32
nullable: true
statutJurid:
type: string
length: 2
nullable: true
capital:
type: string
length: 16
nullable: true
natInscript:
type: string
length: 64
nullable: true
rcsRdm:
type: string
length: 10
nullable: true
gerant:
type: string
length: 1
nullable: true
codeApe:
type: string
length: 4
nullable: true
idIntracomm:
type: string
length: 13
nullable: true
oneToOne:
email:
targetEntity: BodyshopsEmail
joinColumn:
name: id
referencedColumnName: id
BodyshopsEmail.orm.yml
App\Entity\BodyshopsEmail:
type: entity
id:
id:
type: string
length: 2
nullable: false
senderEmail:
type: string
length: 64
nullable: false
fields:
senderName:
type: string
length: 64
nullable: false
replyTo:
type: string
length: 64
nullable: true
smtpHost:
type: string
length: 32
nullable: false
smtpPort:
type: string
length: 6
nullable: false
smtpLogin:
type: string
length: 64
nullable: false
smtpAuth:
type: string
length: 32
nullable: false
smtpSecurity:
type: string
length: 32
nullable: true
popHost:
type: string
length: 32
nullable: true
popPort:
type: string
length: 6
nullable: true
imapHost:
type: string
length: 32
nullable: false
imapPort:
type: string
length: 6
nullable: false
receiveLogin:
type: string
length: 64
nullable: false
receiveAuth:
type: string
length: 32
nullable: false
receiveSecurity:
type: string
length: 32
nullable: false
globalPassword:
type: string
length: 64
nullable: false
signatureFile:
type: string
length: 256
nullable: true
I don't think that's usefull to show you the model, but be sure that every value as a getter and setter (even the $email define by the one-to-one)
You would have no schema changes if you use column already present in your database and model.
For example if you have a table cart with a column customer_id in your existing database
You could do
/**
* One Cart has One Customer.
* #OneToOne(targetEntity="Customer", inversedBy="cart")
* #JoinColumn(name="customer_id", referencedColumnName="id")
*/
private $customer;
You can check using php bin/console doctrine:schema:update --dump-sql to see if there is any sql request needed to do the changes
How can I associate two tables in Sequelize? I tried belongsTo, but this doesn't work. Example:
First table:
users = sequelize.define('users', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
name: Sequelize.TEXT,
type: Sequelize.INTEGER
Second table:
profiles = sequelize.define('profiles', {
id: {
type: Sequelize.INTEGER,
primaryKey: true,
autoIncrement: true
},
place: Sequelize.TEXT,
phone: Sequelize.INTEGER
Association:
profiles.belongsTo(users, {foreignKey: 'id'});
Request:
users.findOne({
where: {name: 'John'},
include: [{model: db.tables.profiles}]
}).then(function(user_data) {
console.log(user_data);
})
Returned [Error: profiles is not associated to users!]
I need to return the matched line of "users" and the line with the same id from the table 'profiles'. Where is the mistake?
You need to declare the association for both tables. From your schema I can't tell what the join condition is. If your profiles table also has a column user_id such that profiles.user_id = users.id, then you could say the following:
users.hasMany(profiles, {
foreignKey: 'id'
});
profiles.belongsTo(users, {
foreignKey: 'user_id'
});
Update
I have now go back to a previous build of doctrine and now the error is:
Invalid schema element named "Roles" at path "RoleResource->columns->relations"
this is whit the same yaml file (see it below)
I have a problem with the doctrine command line tool. When I give the command "build-all-reload", I get te following error:
SQLSTATE[42000]: Syntax error or access violation: 1072 Key column 'role_id' doesn't exist in table. Failing Query: "CREATE TABLE resource (id BIGINT AUTO_INCREMENT, name VARCHAR(20), INDEX role_id_idx (role_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE = INNODB". Failing Query: CREATE TABLE resource (id BIGINT AUTO_INCREMENT, name VARCHAR(20), INDEX role_id_idx (role_id), PRIMARY KEY(id)) DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE = INNODB
My yaml file looks like this:
detect_relations: true
options:
type: INNODB
collate: utf8_general_ci
charset: utf8
Log:
columns:
id:
type: integer
primary: true
autoincrement: true
priority: tinyint
priorityName: string(10)
title: string(250)
message: text
actAs:
Timestampable:
created:
type: timestamp
format: Y-m-d H:i:s
updated:
disabled: true
User:
columns:
id:
type: integer
primary: true
autoincrement: true
username: string(50)
password: string(40)
actAs:
Timestampable:
created:
type: timestamp
format: Y-m-d H:i:s
updated:
type: timestamp
format: Y-m-d H:i:s
Role:
columns:
id:
type: integer
primary: true
autoincrement: true
name: string(20)
attributes:
export: all
validate: true
RoleResource:
columns:
role_id:
type: integer
primary: true
resource_id:
type: integer
primary: true
relations:
Role:
foreignAlias: RoleResource
Resource:
foreignAlias: RoleResource
Resource:
columns:
id:
type: integer
primary: true
autoincrement: true
name: string(20)
relations:
Roles:
foreignAlias: Resources
class: Role
refClass: RoleResource
Menu:
columns:
id:
type: integer
primary: true
autoincrement: true
label: string(20)
Artical:
columns:
id:
type: integer
primary: true
autoincrement: true
title: string
content: longtext
css: longtext
js: longtext
I don't know how to solve this problem.
Can someone please help me?
I downgraded Doctrine.
And there are to spaces to much in the yaml file add the line:
relations:
from the component "RoleResource:"
Thank you for all the help Tom,
Ivo Trompert