MVC: The INSERT statement conflicted with the FOREIGN KEY constraint - database

I have two tables that are supposed to be related.
Tables and Coloums Specification
Primary key table
ProductCategory
ProductCategoryID
Foreign key table
SubProductCategory2
ProductCategoryID
In the controller I have the following methods when creating sub category...
public ActionResult Create()
{
ViewBag.ProductCategory = db.ProductCategories.OrderBy(p =>
p.ProductCategoryID).ToList();
ViewBag.SubProductCategory2 = db.SubProductCategory2.OrderBy(a =>
a.ProductCategoryID).ToList();
var PC2 = new SubProductCategory2();
return View(PC2);
}
public ActionResult Create(SubProductCategory2 Createsubcat2,
FormCollection values)
{
if (ModelState.IsValid)
{
db.AddToSubProductCategory2(Createsubcat2);
db.SaveChanges();
//error pointing here and the full error message I am getting is...
/*error: System.Data.SqlClient.SqlException:
* The INSERT statement conflicted with the FOREIGN KEY constraint
* "FK_SubProductCategory2_ProductCategory". The conflict occurred in
* database "MyHouseDB", table "dbo.ProductCategory", column
* 'ProductCategoryID'. The statement has been terminated.*/
return RedirectToAction("/");
}
ViewBag.ProductCategory = db.ProductCategories.OrderBy(p =>
p.ProductCategoryID).ToList();
ViewBag.SubProductCategory2 = db.SubProductCategory2.OrderBy(a =>
a.ProductCategoryID).ToList();
return View(Createsubcat2);
}
ViewBag.ProductCategory = db.ProductCategories.OrderBy(p =>
p.ProductCategoryID).ToList();
ViewBag.SubProductCategory2 = db.SubProductCategory2.OrderBy(a =>
a.ProductCategoryID).ToList();
return View(Createsubcat2);
in the views I have the following code...
<div class="editor-label">
#Html.LabelForModel()
</div>
<div class="editor-field">
#Html.DropDownList("CategoryName", new
SelectList((System.Collections.IEnumerable)ViewData["ProductCategory"],
"ProductCategoryID", "CategoryName"))
#Html.ValidationMessageFor(model => model.ProductCategory.CategoryName)
Could some tell me how to solve the The INSERT statement conflicted with the FOREIGN KEY constraint error message. Correct me if I'm wrong, have I created the relationship between two tables incorrectly or the problem else where? Thanks in advance.

This error happens when the following conditions are true 1) The value that you selected for "ProductCategoryID" is not present in the "ProductCategory" table OR 2) The product category table is empty.
Does you have values in the product category table?
What value are you choosing for ProductCategoryID?

I have found the problem. It was my sql database design not MVC coding side. I removed CategoryName column from SubCategory table. I could have felt the CategoryName as long as Allow Null was set to true. There was no point in doing that has PrimaryKey had been setup correctly for the two tables.

Related

How can I display certain rows of a data table?

When displaying my CollectionView (which contains the data), I would like to display only the rows that have the field "Number" = xx
Currently I display my data like this:
public async Task<List<DB_PosteNF>> ListerPF()
{
try
{
return await connection.Table<DB_PosteNF>().ToListAsync();
}
catch (Exception ex)
{
StatutMessage = $"Impossible d'afficher la liste des postes de frais. \nErreur : {ex.Message}";
}
return new List<DB_PosteNF>();
}
Here is the structure of my tables, I would like Primary Key number = Foreign Key
Table 1:
Primary Key = Number
Table 2:
Primary Key = Id
Foreign key = Number
Use LINQ
connection.Table<DB_PosteNF>().Where(x => x.Number == SomeValue).ToListAsync();
Replace SomeValue with value you want to filter by

CakePHP 3.x Query many Table objects with Pagination

Context:
I'm working with CakePHP 3.x and I'm trying to build an ORM query with pagination. I have the tables Users, Topics and Areas. User can have many topics but just one area. This is the db model:
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
email VARCHAR(255) NOT NULL,
password VARCHAR(255) NOT NULL,
);
CREATE TABLE topics (
id INT AUTO_INCREMENT PRIMARY KEY,
user_id INT NOT NULL,
name VARCHAR(255),
description TEXT,
FOREIGN KEY user_key (user_id) REFERENCES users(id)
);
CREATE TABLE areas (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255),
UNIQUE KEY (title)
);
CREATE TABLE users_areas (
user_id INT NOT NULL,
area_id INT NOT NULL,
PRIMARY KEY (user_id, area_id),
FOREIGN KEY area_key(area_id) REFERENCES areas(id),
FOREIGN KEY user_key(user_id) REFERENCES users(id)
);
What I need
I need to get all the Topics filtered by an area given.
I'm trying the next:
//1. get the area from the url (OK)
$area = $this->request->getQuery('area');
//2. Get the area from db to get the id
$myarea = $this->Areas->find()->where(['title' => $area])->first();
//3. Get all the users related to the area given
$users = $this->Users->find()->matching('Areas', function ($q){
return $q->where(['Areas.id' => $myarea->id]);
});
//4. Get the Topics and Paginate
$topics = $this->paginate($this->Topics->find('all')->innerJoinWith('Users', function ($q){
return $q->where(['User.id' => $myarea->id]);
}));
//5. Set the topics (OK)
$this->set(compact('topics'));
$this->set('_serialize', ['topics']);
I got tons of errors and I'm not sure how to build the query properly.
At first glance, there's at least one mistake:
$myarea is invisible inside anonymous function.
If You wanna use $myarea inside lambda function, You should inherit this variable from parent scope: use($var).
http://php.net/manual/en/functions.anonymous.php example #3
$users = $this->Users->find()->matching('Areas', function ($q) use ($myarea) {
return $q->where(['Areas.id' => $myarea->id]);
});
$topics = $this->paginate($this->Topics->find('all')->innerJoinWith('Users', function ($q){
return $q->where(['User.id' => $myarea->id]);
}));

Getting the generated key for a multi-column primary key in JDBC

I want to get the generated key from an insert.
My code:
stmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
ResultSet generatedKeys = stmt.getGeneratedKeys();
int columnCount = generatedKeys.getMetaData().getColumnCount();
if (generatedKeys.next()) {
do {
for (int i=1; i<=columnCount; i++) {
String key = generatedKeys.getString(i);
System.out.println("KEY " + generatedKeys.getMetaData().getColumnName(i) + " = " + key);
}
} while(generatedKeys.next());
}
This works fine.
My question is now: When I have a table with a multiple primary key, the value is always null. Why is this so?
The getGeneratedKeys() method is intended to return the key values that are automatically generated by the database when inserting into a table with a single "Identity" column (a.k.a. "AutoIncrement", "AutoNumber", and probably key values generated by a Sequence as well).
Depending on the implementation details of the JDBC driver, it might be possible to retrieve other automatically-generated primary key values, e.g., if a multi-column primary key value was assigned by an INSERT trigger or some other mechanism. However, that is not particuarly likely and certainly not something that you could count on.
And of course, if the primary key value is not automatically generated (as in your case) then it should come as no surprise that getGeneratedKeys() does not return anything because there is nothing to return.

One to Many relationship using breezejs

I have the following one to many relationship setup between two tables (Case and Recipient)
Case table has one primary key which is identified as an identity (auto-increment) tblRecipient has one primary key which is identified as an identity (auto-increment),and a foreign key relationship with Case.
Case table and related tblRecipient data is pulled:
function searchCases(caseID, caseNum)
{
var qPredicate;
if (caseID != '')
{
qPredicate = new breeze.Predicate("pkCaseID", "==", parseInt(caseID));
}
else if (caseNum != null)
{
qPredicate = new breeze.Predicate("CaseNumber", "Contains", caseNum);
}
var query = breeze.EntityQuery
.from("case")
.where(qPredicate)
.expand("tblRecipients")
return manager.executeQuery(query);
}
When a button is pressed to add a new recipient, the following code is used to create a new recipient entity:
function createNewRecipient(CaseID)
{
var recipientEntityType = manager.metadataStore.getEntityType("tblRecipient");
var newRecipient = manager.createEntity(recipientEntityType, {fkCaseID: CaseID});
return newRecipient;
}
This code returns this error:
Error: Cannot attach an object to an EntityManager without first setting its key or setting its entityType 'AutoGeneratedKeyType' property to something other than 'None'
The AutoGeneratedKeyType in the metadata shows None instead of Identity as in the Case table. We are not sure what we need to change or how to really debug this. Any help would be appreciated.

Cake HABTM not deleting rows in join table correctly

This has been causing me considerable grief for a couple of days now, so I turn to the community for help.
Assume two tables - Album HABTM Customer
The join table is customer_albums PK(album_id, customer_id)
I have two controller functions:
public function like($album_id) {
if ($this->request->is('post')) {
$this->Album->CustomerAlbum->save(array('album_id' => $album_id,'customer_id' => $this->Auth->user('id')));
$this->redirect(Controller::referer());
}
}
and this one...
public function unlike($album_id) {
$this->log($album_id);
if ($this->request->is('post')) {
$this->Album->CustomerAlbum->deleteAll(array('album_id' => $album_id,'customer_id' => $this->Auth->user('id'),false));
$this->redirect(Controller::referer());
}
}
The "Like" function results in the SQL:
INSERT INTO gre49302_digital.customer_albums (album_id, customer_id) VALUES (1, 62)
which is what I would expect.
However, the "Unlike" function results in:
SELECT CustomerAlbum.album_id FROM gre49302_digital.customer_albums AS CustomerAlbum WHERE album_id = 1 AND customer_id = 62
DELETE CustomerAlbum FROM gre49302_digital.customer_albums AS CustomerAlbum WHERE CustomerAlbum.album_id = (1)
Which indicates to me that CakePHP doesn't understand the concept of a compound primary key.
Consequently when attempting to delete one "like" between customer and album, I end up deleting everything for the selected album.
Ideally the "unlike" function should simply delete a single record from customer_albums using a compound primary key as selector.
This could possibly be the cause. Your current code is:
deleteAll(array('album_id' => $album_id, 'customer_id' => $this->Auth->user('id'), false));
I'm going to assume you meant to set cascade to false. If that is the case, you have the wrong order of close parentheses.
Change your code to:
deleteAll(array('album_id' => $album_id, 'customer_id' => $this->Auth->user('id')), false);
Note the ('id')), false) vs ('id'), false)).

Resources