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,
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 id
$emp->employeeTypes()->associate($request->employee_types_id);
Now let's see what the advantages and disadvantages of the methods are:
1. Setting the foreign key manually
- Pro: It's the simplest method
- Contra: You have to explicitly use the foreign key column name
2. Using associate()
with the model
- Pro: The relationship will be set automatically so you can use the model later without first fetching it from the database
- Pro: The name of the foreign key column doesn't matter (it only needs to be defined in the relationship declaration)
- Contra: An extra query is necessary to fetch the related model first
3. Using associate()
with just the id
- Pro: The name of the foreign key column doesn't matter (it only needs to be defined in the relationship declaration)
- Contra: The relationship won't be loaded after associating the id. A query will run when you access
$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.