Search code examples
phplaraveleloquentforeign-keyscircular-reference

Adding in two elements in eloquent db with circular foreign keys


Hi I was wondering how I could create two elements whom's foreign keys form a circular structure in eloquent php (laravel). I have two tables, persons and actions these are there structures (mock up) :

persons :

key value
id bigint auto increment
name varchar(255)
last_action_id bigint

Foreign key : last_action_id → actions(id)

actions :

key value
id bigint auto increment
description varchar(255)
person_id bigint

Foreign key : person_id → persons(id)

I would like to create a new person and his/her first action. Does anyone know how to accomplish this. Thanks in advance.


Solution

  • Whilst you've not given a massive amount of information, I don't see why you would need to do it this way. Each person has many actions, presumably, so set up the relationships accordingly :

    In your Person model :

    public function actions() { 
        return $this->hasMany(Action::class);
    }
    

    In your Action model :

    public function person() { 
        return $this->belongsTo(Person::class);
    }
    

    Then to retrieve their last action you could just instantiate your person, get their actions, then retrieve the last of those using :

    $person->actions->last();