jeudi 17 mai 2018

Where and how to create laravel model relationships

I am developing a new system in Laravel which makes use of data in an existing database.

The new system has its own database with some tables that hold data relating to a record in another table in the existing database.

I have an eloquent model in the Laravel app which models the table in the existing database and defines its relationships to the tables in the new database.

class Existing extends Model
{
  public function relationshipA()
  {
    return $this->hasOne(RelationshipA::class);
  }

  public function relationshipB()
  {
    return $this->hasOne(RelationshipB::class);
  }

  ...
}

I am looking for a way to create the table entries for these relationships if an entry does not already exist. The purpose for this is to prepopulate the fields in a form they represent with some default sensible data.

From what I have read on the Laravel documentation, I can make use of withDefault(), however, using withDefault() I don't get a relationship I get a half-baked representation (no primary key, timestamps etc.).

I have tried the following:

public function relationshipA()
{
  return $this->hasOne(RelationshipA::class)
    ->withDefault(function ($model) {
      return $model->save();
  });
}

This works in creating the relationship the first time, however, throws an integrity constraint violation on the foreign key column thereafter as the relationship already exists. Removing the constraint results in multiple records being created which I don't want.

Where and/or how should I be creating these relationships?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire