I have two tables, employees
and employee types
.
employees
has the following fields
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:
associate()
with the modelassociate()
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With