mardi 29 novembre 2016

Enforcing one to one relationships in Laravel

I am creating an app in Laravel 5.

The app I'm creating is a recruitment site where a candidate must fill many forms. Because there are many fields, I decided to logically partition the users into many tables with one-to-one relationships.

For example:

users

  • id
  • role (e.g. admin or candidate)
  • first_name
  • surname
  • DOB

driving_licences

  • id
  • user_id (FK to users)
  • has_licence
  • number_of_points
  • licence_number

In the above simple case, the users has a one-to-one relationship to driving_licences. In other words, every User MUST have a single corresponding DrivingLicence row.

Creating the above table and corresponding Eloquent models is simple enough. However I am struggling as to the best approach to enforce that every user (or every user who is a candidate) has a corresponding DrivingLicence.

The solution I have currently is, whenever I use something from DrivingLicence I first check if the relationship exists and create it if it doesn't like so:

if ($user->drivingLicence === null) {
    $drivingLicence = new DrivingLicence();
    $drivingLicence->user_id = $user->id;
    $drivingLicence->save();
}

This has to be done every time I need to do something with DrivingLicence, which of course creates a LOT of repetition.

Therefore, my question is, how can I enforce that a one to one relationship exists between users and driving_licences.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire