Difference between setting an ID directly and setting an eloquent association relationship when saving a model in Laravel?

I have two tables, employeesand employee types.

employees has the following fields

  • id (PK)
  • employee_type_id (FK)
  • name

and employee_typehave the following fields:

  • id (PK)
  • title

My eloquent model features:

Employee

  class Employee extends Model {

    public function employeeTypes() {
        return $this->belongsTo('App\Model\EmployeeType');
    }
}

EmployeeType

class EmployeeType extends Model {
}

I'm not sure if this is the right way to maintain a relationship. When pasting, I can do the following two methods:

1.Create an identifier

 $emp = new Employee();
 $emp->employee_type_id = $request->type_id;
 $emp->name = $request->name;
 $emp->save();

2. Establishing a relationship

$emp->employeeTypes()->associate(EmployeeType::findOrFail($request->employee_types_id));
$emp->name = $request->name;
$emp->save();

Both methods work fine.

What is the difference between these two types of inserts?

What is the best method?

+4
source share
1 answer

Before comparing the parameters, there is a third:

Using associate()only with id

$emp->employeeTypes()->associate($request->employee_types_id);

, :

1.

  • Pro:
  • Contra:

2. associate()

  • Pro: ​​, ,
  • Pro: ( )
  • Contra: , .

3. associate() id

  • Pro: ( )
  • Contra: . $emp->employeeTypes

associate() ( , ). , , . .., .

+6

All Articles