I'm new to the hasAndBelongsToMany relationships in CakePHP. I'm trying to figure out the best way to implement the following scenario. Do I use hasAndBelongsToMany or hasMany through?
In my application I am creating Repair Orders. The Repair Orders have Op Codes, which are assigned to employees. There can be more than one Op Code per Repair Order. So, it's likely I'll have something similar to the following:
RepairOrder1 - OpCode1 completed by Employee1, OpCode2 completed by Employee2
From what I read in the manual, the reason you can't use HABTM relationships for this type of situation is that when saving the data, the original information is removed first. However, in 2.1 there is a 'unique' key that you can set to have it keep the existing information first. So do I create a HABTM or a hasMany through?
EDIT
Here's my schema:
/* repair_orders */
CREATE TABLE repair_orders (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
number VARCHAR(16), //Auto-generated repair order number
created DATETIME DEFAULT NULL,
modified DATETIME DEFAULT NULL
);
/* Employees */
CREATE TABLE employees (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(16),
created DATETIME DEFAULT NULL,
modified DATETIME DEFAULT NULL
);
/* op_codes */
CREATE TABLE op_codes (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(16),
sale_material DECIMAL(10,2),
cost_material DECIMAL(10,2),
created DATETIME DEFAULT NULL,
modified DATETIME DEFAULT NULL
);
I am trying to assign more than one op code to the repair orders, and also keep track of which employee did that specific op code. So I can have a repair order with 3 op codes, each with a different employee. So I think that requires another table, something like:
/* repair_order_assignments */
CREATE TABLE repair_order_assignments (
id INT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
repair_order_id INT(16),
op_code_id INT(16),
employee_id INT(16)
);
So my associations would be:
Repair_Order_Assignment hasMany Employee, Op_Code
Employee belongsTo Repair_Order_Assignment
Op_Code belongsTo Repair_Order_Assignment
Repair_Order_Assignment hasAndBelongsToMany Repair_Order
Repair_Order hasAndBelongsToMany Repair_Order_Assignment
Then according to the manual, when hasAndBelongsToMany associations are saved, the association is deleted first. You would lose the extra data in the columns as it is not replaced in the new insert. However, it goes on to note that in 2.1 there is a unique variable that can be set to save the extra data. Will this setup work with the unique key or should I use a hasMany through approach?