Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between setting ID directly and setting eloquent associate relation when saving a model in Laravel?

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?

like image 477
gsk Avatar asked Jul 09 '15 06:07

gsk


1 Answers

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.

like image 116
lukasgeiter Avatar answered Sep 17 '22 20:09

lukasgeiter