Linq to Sql How To delete table along with all relationships - linq-to-sql

I have a table "User" With a relationship to around 7 other tables. If I try to delete the user it won't let me unless I delete all the data in the other tables that has a userId. Is there a way to delete everything automatically without having to delete each one of the tables with that UserId one table at a time?

You can use cascade delete.
Code first: In OnModelCreating method of context class:
modelBuilder.Entity<Table1>()
.HasOptional(c => c.User)
.WithMany(c => c.Table1s)
.HasForeignKey(c => c.UsereID).WillCascadeOnDelete(true);
modelBuilder.Entity<Table2>()
.HasRequired(c => c.User)
.WithMany(c => c.Table2s)
.HasForeignKey(c => c.UsereID).WillCascadeOnDelete(true);

Related

Laravel Eloquent create method skipping IDs and returning them

I'm simply trying to create a new model through Eloquent's create method. However, we're seeing that the new model will sometimes contain an id that has been skipped in mysql. This id is designated as an autoincrement column in mysql.
We are also seeing this happen when using DB:getPdo()->lastInsertId() immediately after the model has been created.
$questionResponse = $response->questionResponses()->create([
'survey_question_id' => $question->id,
'response' => 5
]);
$response_id = $questionResponse->id; // weve also used DB::getPdo()->lastInsertId();
Queue::push('TheWorker', array('survey_id' => $survey->id, 'response_id' => $response_id, 'question_id' => $question->id, 'user_id' => $user->id, 'student_target_id' => $student_target_id));
TheWorker then fails due to receiving an incorrect $repsonse_id that doesn't exist in the DB.
We would expect that the newly created model would contain the id that matches the record created in mysql.
Thanks in advance!

Yii2 GridView display only related records

I have this database structure:
I need the user to get only those reservations in ReservationsSeachModel that are in the warehouse belonging to the user. Model user_has_warehouse has a function getUserHasWarehouse($user_id, $warehouse_id) to check for relations. I am able to get the relations when viewing single, deleting and updating records in controllers. But I cannot make the SearchModel to return reservations that belong to current user.
I cannot depend on Reservation->user_id, because that value is not mandatory and reservations can be inserted publicly with no user_id. How to make the SearchModel work properly so it only shows reservations belonging to the warehouse where user has the warehouse?
ReservationsSearchModel:
$warehouse_id = User_Has_Warehouse::find()->select(['warehouse_id'])->where(['user_id' => Yii::$app->user->id]);
$freezer_type_id = Freezer_type::find()->select(['id'])->where(['warehouse_id' => $warehouse_id]);
$reservation_id = Reservation_freezer_type::find()->select(['reservation_id'])->where(['freezer_type_id'=>$freezer_type_id]);
...
$query->andFilterWhere([
'id' => $reservation_id,
'customer_id' => $this->customer_id,
'user_id' => $this->user_id,
]);
...
But the following did not work for me. What am I doing wrong?
Managed to solve it.
$h = User_Has_Warehouse::find()->select(['warehouse_id'])->where(['user_id' => Yii::$app->user->id]);
$rt = Freezer_type::find()->select(['id'])->where(['warehouse_id' => $h]);
$res = Reservation_freezer_type::find()->select(['reservation_id'])->where(['freezer_type_id' => $rt]);
// grid filtering conditions
$query->andFilterWhere(['id' => $res]);

Delete multiple rows in YII2

I have an array of objects fetched from database:
$masterListContacts = MasterListContacts::find()
->select('master_list_contacts.*')
->innerJoin('master_contacts', '`master_contacts`.`id` = `master_list_contacts`.`master_contact_id`')
->with('masterContact')
->where(['user_id' => \Yii::$app->user->identity->id, 'slug' => $slug])
->all();
Under certain circumstances, I need to delete all rows from the database represented in this array. But with both delete() and deleteAll() methods I got an error Call to a member function ... on array. Could someone tell me please which one is the best way to accomplish this?
UPDATE:
Here is my database structure.
Found better solution:
\Yii::$app
->db
->createCommand()
->delete('master_contacts', ['id' => $deletableMasterContacts])
->execute();
Where $deletableMasterContacts is array of master_contacts ids, which should be deleted
You can painlessly remove ->select('master_list_contacts.*').
->innerJoin('master_contacts', '`master_contacts`.`id` = `master_list_contacts`.`master_contact_id`')
performs the same work that ->joinWith('masterContact').
For delete entites try use this code:
MasterListContacts::deleteAll(['user_id' => \Yii::$app->user->identity->id, 'slug' => $slug]);

Doctrine cascade delete query?

I am using following query to delete countries in my database but it is giving foreign key error because countries has one to many relationship with cities.
I am using following query :
$cd = 1;
Doctrine_Core::getTable('country')->find($cd)->delete();
this query soft deletes if countries doesn't have any child but gives error if countries have any city.
I have also done following settings in country model:
$this->hasMany('city', array(
'local' => 'id',
'foreign' => 'country_id',
'cascade' => 'delete'
));
Please suggest.
In BaseCity.php you should have a relation to Country. In:
$this->hasOne('Country', array(
...
add this line:
"onDelete"=>"CASCADE"
When you delete country, cities will be deleted too. If you want to keep them, put
"onDelete"=>"SET NULL"
I think above way is also correct but I solved it in following way.
I made relation of country to city like this :
$this->hasMany('city', array(
'local' => 'id',
'foreign' => 'country_id',
'cascade' => array(
0 => 'delete',
)));
In YAML file I added like this :
cascade: [delete]
and it worked.

CakePHP and referential integrity

My DB server doesn't support innodb engine, so I can't use Foreign key
costraints at DB level.
How can I assure referential intergrity? Can I do this using cakephp model,
how?
As long as you define your model associations properly, you should be ok. If you're worried about orphan records when deleting records, you can set 'dependent'=> true in your associations.
http://book.cakephp.org/view/1039/Associations-Linking-Models-Together#hasMany-1043
I'm using myISAM engine on my tables with cakePHP, had no problems so far =).
foreign keys are defined in model like this:
// this is a property of Post Model
var $belongsTo = array(
'PostCategory' => array(
'className' => 'PostCategory',
'foreignKey' => 'post_category_id',
'conditions' => '',
'fields' => '',
'order' => ''
)
);
this means that current model is associated with PostCategory model using post_category_id column as a foreign key.