DoctrineORM : Error while inserting data into a table which has foreign key attribute - mysql

I have the following database structure given by
The "subcat_id" column in the "Course" table points to the "id" column in the "sub_category" table.
The "instructort_id" column in the "Course" table points to the "id" column in the "user" table.
I want to insert data in the "course" table. I am using Symfony2 framework with Doctrine as the database library. When I try to insert data into the course table using the following statements:
$newCourse=new \FrontEndBundle\Entity\Course;
$newCourse->setSubcat($data['subcat']);
$newCourse->setName($data['coursename']);
$newCourse->setInstructor($instructorId);
$newCourse->setDescription($data['description']);
$em->persist($newCourse);
$em->flush();
, I get an error($newCourse is an object of the Course Entity class)
Error shown is displayed below:
I think the error relates to foreign key issues. Can anyone help me on how can I insert data
In the course table correctly?
Thanks in advance..!!

this problem is because you are passing a id, which is not a SubCategory object to your setter in the SubCategory entity
so, you have to retrieve you SubCategory object first, then set it to the Course entity
try this way
$subCat = $this->getDoctrine()
->getRepository('FrontEndBundle:SubCategory')
->find($data['s‌​ubcat']);
and then
$newCourse->setSubcat($subCat);

Related

Delete many2many column in table and the table itself - odoo 13

While running a pre-migration script to delete a (wizard) transient model, ended up with below mentioned issue.
from openupgradelib import openupgrade
#openupgrade.migrate()
def migrate(env, version):
openupgrade.delete_records_safely_by_xml_id(
env,
["moduel_name.view_id)"],
delete_childs=True,
)
try:
env.cr.execute("DROP TABLE IF EXISTS table_name CASCADE")
env.cr.execute("DROP TABLE IF EXISTS dependent_table_names CASCADE")
except Exception as e:
raise ("Exception--------------", e)
Error:
psycopg2.errors.ForeignKeyViolation: update or delete on table "ir_model" violates foreign key constraint "ir_model_relation_model_fkey" on table "ir_model_relation"
Similar issue: https://github.com/odoo/odoo/issues/54178
According to the above issue, having Many2many in transient model might cause this issue. It is true in my case as well. I have many2many fields. No solution there.
I kind of tried deleting the problematic fields(Many2many) before deleting columns. But it is known that many2many fields can't be located in db. kind of stuck.
openupgrade.drop_columns(
env.cr,
[
("table_name", "any_other_column_name"), # ---> This works
("table_name", "many2many_column_name"), # ---> This doesn't
],
)
is there anyway to get rid of many2many fields from the model ? Any help is appreciated.
Could you try this :
Let's say your Transient is my_transient_model and the Many2many field is e.g. sale_line_ids = fields.Many2many('sale.order_line')
First thing to know : Did you specify the relation table ? like
sale_line_ids = fields.Many2many('sale.order_line', 'my_relation_table_name') ?
If so, 'my_relation_table_name' is the name you want to delete from ir_model_relation.
If not, the relation table name is my_transient_model_sale_order_line_rel (so model then _ then the model we point to with _ instead of . then _rel.
Second set: delete the data from ir_model_relation:
DELETE FROM ir_model_relation WHERE name='my_transient_model_sale_order_line_rel';
Then you should be able to delete the Many2many table :
DROP TABLE my_transient_model_sale_order_line_rel;
(for sure, change my_transient_model_sale_order_line_rel if you specified the relation table like my_relation_table_name in the example)
Hope it helped, keep me updated :)

when defining a table in SequelizeJs its name is changed when executing

when defining a table in SequelizeJs its name is changed when executing resulting in a ER_NO_SUCH_TABLE.
This is my code :
var API_TOKEN=database.sequelize.define('API_TOKENS',{
user_id:{
type:Sequelize.INTEGER,
},
token:{
type:Sequelize.STRING
}
});
and the error :
Unhandled rejection SequelizeDatabaseError: ER_NO_SUCH_TABLE: Table 'tableName.API_TOKENs' doesn't exist
Note:notice how the table name is changed when executed , i am using mysql database.
You can use one of two available options that can be put in the options of sequelize.define method
freezeTableName
tableName
According to the sequelize documentation (concerning how it names the database table basing on model definition)
By default, sequelize will automatically transform all passed model names (first parameter of define) into plural.
By using the freezeTableName, the database table will be named exactly the same as your model name. On the other hand, if you want fully custom table name, you should use the tableName attribute.

How to correctly define one-to-many relations with existing joint table using node Sequelize

I am using Sequelize, but since I also have other servers running other than node.js, I need to let them share the database. So when defining one-to-many relation, I need to let Sequelize use the old existing jointTable.
I write my definition of the association as below, where pid is the primary key of presentations:
this.courses.hasMany(this.presentations,
{as : 'Presentations',
foreignKey : 'cid',
joinTableName : 'course_presentations'
});
Or this one:
this.courses.hasMany(this.presentations,
{as : 'Presentations',
foreignKey : 'pid',
joinTableName : 'course_presentations'
});
I am using the below codes to retrieve the associated presentations:
app.get('/courses/presentations/:cid', function (req, res){
var cid = req.params.cid;
app.models.courses.find({where: {cid:cid}}).success(function(course){
course.getPresentations().success(function(presentations){
res.send(presentations);
});
});
});
The previous one will tell me there is no cid in 'presentations' table.
The latter one will give something like this:
Executing: SELECT * FROM `courses`;
Executing: SELECT * FROM `courses` WHERE `courses`.`cid`='11' LIMIT 1;
Executing: SELECT * FROM `presentations` WHERE `presentations`.`pid`=11;
Check carefully, I found that everytime, it is always using the cid value to query for presentations, which means only when they happen to share the same id value, something can be returned. And even for those, it is not correct.
I am strongly suspecting, Sequelize are not using the joinTable I specified, instead, it is still trying to find the foreign keys in the original two tables. It is viewing pid as the reference of cid in presentations, which causes this problem.
So I am wondering how to correctly set up the junction table so that the two of them can use the foreign keys correctly.
jointTableName : 'course_presentations'
should be (without a t)
joinTableName : 'course_presentations'
Actually AFAIK - this kind of relation is not "pure" one-to-many.
You have one course can have many entries in course_presenation table, and course_presentation have one-to-one relation with presentation. If so, just define that kind of associations in model.

Entity Framework related objects insertion with stored procedure and auto_increment field

I have a problem inserting a related row through Entity Framework 5. I'm using it with RIA Services and .NET Framework version 4.5. The database system is MySQL 5.6. The connector version is 6.6.5.
It raises a Foreign Key constraint exception.
I've chosen to simplify the model to expose my issue.
LDM
Provider(id, name, address)
Article(id, name, price)
LinkToProvider(provider_id, article_id, provider_price)
// Id's are auto_increment columns.
First I create a new instance of Article. I add an instance of LinkToProvider to the LinkProvider collection of the article. In this LinkToProvider object the product itself is referenced. An existing provider is also referenced.
Then I submit the changes.
Sample code from the DataViewModel
this.CurrentArticle = new Article();
...
this.CurrentArticle.LinkToProvider.Add(
new LinkToProvider { Article = this.CurrentArticle, Provider =
this.ProviderCollection.CurrentItem }
);
...
this.DomainContext.articles.Add(this.CurrentArticle);
this.DomainContext.SubmitChanges();
NOTE :
At the begining Entity Framework inserts the product well. Then it fails because it tries to insert a row in the LinkToPrivder table with an unkown product id like the following.
INSERT
INTO LinkToProvider
VALUES(5, 0, 1.2)
It puts 0 instead of the generated id.
But if I insert a product alone without any relations the product id is generated in the database correctly.
Any help will be much appreciated !
Thank you.
I found the answer.
You need to bind the result from the stored procedure to the id column in the edmx model
So I have to modify my stored procedure to add an instruction to show the last instered id for the article table on the standard output.
SELECT LAST_INSERT_ID() AS NewArticleId;
Then I added the binding with the name of the column name returned by the stored procedure. Here it's NewArticleId.
It's explained here : http://learnentityframework.com/LearnEntityFramework/tutorials/using-stored-procedures-for-insert-update-amp-delete-in-an-entity-data-model/.

Propel ORM with Two FK Columns To Same Foreign Table

I have a table that contains two foreign keys that map back to a membership table. They are named "from_member" and "to_member."
I am trying to get the Member object that represents this membership table by doing something like:
$feedbackQuery = FeedbackQuery::create()->findOne();
$fromMember = $feedbackQuery->getFromMember();
So that I can go like this:
$firstName = $fromMember->getFirstName();
The only problem is you can't do that, evidently Propel requires you to call $fedbackQuery->getMember()and who knows what that's going to return in this case.
Is there any easy way to accomplish getting the member data like this?
Assuming that you are using from_member_id and to_member_id as your foreign keys, you should have two methods at your disposal. getMemberRelatedByToMemberId() and getMemberRelatedByFromMemberId().
To find your from_member object and to use it.
$fromMember = $feedbackQuery->getMemberRelatedByToMemberId();
$firstname = $fromMember->getFirstName();