I have two tables, employees
and employee types
.
employees
has the following fields
- id (PK)
- employee_type_id (FK)
- name
and employee_type
has the following fields,
- id (PK)
- title
My eloquent model functions are,
Employee
class Employee extends Model {
public function employeeTypes() {
return $this->belongsTo('App\Model\EmployeeType');
}
}
EmployeeType
class EmployeeType extends Model {
}
I am not sure if this is the correct way to keep a relation. While inserting I can follow these two methods:
1.Setting ID
$emp = new Employee();
$emp->employee_type_id = $request->type_id;
$emp->name = $request->name;
$emp->save();
2.Setting relation
$emp->employeeTypes()->associate(EmployeeType::findOrFail($request->employee_types_id));
$emp->name = $request->name;
$emp->save();
Both methods are working fine.
What is the difference between these two types of insertion?
Which is best method?
Before I compare the options, there is a third one:
Using
associate()
with just the idNow let's see what the advantages and disadvantages of the methods are:
1. Setting the foreign key manually
2. Using
associate()
with the model3. Using
associate()
with just the id$emp->employeeTypes
I personally prefer to use
associate()
(basically all relationship methods, even if they aren't always necessary). If I already have the model I pass that, and otherwise I'll just use the id. You already have defined your relationship with foreign key etc, so you might as well use it.