Two Methods of Updating Intermediate Association Table Data in PHP
- 2021-07-16 02:02:08
- OfStack
This article shows two ways PHP implements updating the data of the intermediate association table in the form of examples. Share it with you for your reference. The specific methods are as follows:
First of all, the intermediate association table: here, the intermediate table only stores the primary key of Table 1 and the primary key of Table 2, that is, the many-to-many form.
Performing data addition and deletion is an internal method of the framework, which is not part of the thinking.
Method 1: Delete all the old data first, and then add new data
$res = $this->classes->classEdit($id, $data); // Modify master table data
if($res)
{
// Delete the associated table data first
$bool = $this->lesson_classes->lessonClassesDel($id);
if($bool)
{
// Loop to assemble conditions and add data
foreach($lesson_ids as $val)
{
$arr = array('class_id'=>$id, 'lesson_id'=>$val); // Data
$res = $this->lesson_classes->lessonClassesAdd($arr); // Perform add
}
}
$this->show_tips(' Operation successful! ');
}
else
{
$this->show_tips(' Operation failed! ');
}
The disadvantage of using this method is that it is unsafe to delete data in large quantities, and there is a certain degree of potential safety hazard.
Method 2: Add only what you need and delete only what you want to delete
// Old data found in the library: $arr_old ( Treated 1 Dimensional array )
// New data submitted: $arr_new ( Get 1 Dimensional array )
$intersect = array_intersect($arr_old, $arr_new); // Intersection (the part that needs to be preserved does not need to be processed)
$result_del = array_diff($arr_old, $intersect); // What needs to be deleted in the old data
$result_add = array_diff($arr_new, $intersect); // What needs to be added in the new data
// Add new data
if($result_add && is_array($result_add))
{
foreach($result_add as $val)
{
$data_add = array('class_id'=>$id, 'lesson_id'=>$val); // Data
$bool_add = $this->lesson_classes->lessonClassesAdd($data_add); // Perform add
}
}
// Delete data to be purged
if($result_del && is_array($result_del))
{
foreach($result_del as $val)
{
$bool_del = $this->lesson_classes->lessonClassesDel($id, $val); // Perform a delete
}
}
if($bool_add && $bool_del)
{
$this->show_tips(' Operation successful! ');
}
else
{
$this->show_tips(' Operation failed! ');
}
The method has the characteristics of adding and deleting data pertinently. Compared with the first method, the method has higher security
I hope this article is helpful to everyone's PHP programming.