xtremer360
2 years ago
83
14
Laravel

Pivot Table and Syncing

Posted 2 years ago by xtremer360

What I'm trying to accomplish is that when a new patient is entered into the database it will also save which conditions the patient has. I have a pivot table set up for this right now called "conditions_patients" with fields of condition_id and patient_id. I'm not sure if I should either add an additional row so that if the patient has that condition then there will be a 1 for that additional field or if I should just enter into this table if the patient has the condition with the condition_id and their patient_id.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Patient extends Model
{
    protected $table = 'patient_data';
    protected $guarded = 'id';

    public function account()
    {
        return $this->belongsTo('App\User', 'user_id');
    }

    public function conditions()
    {
        return $this->belongsTo('App\Condition', 'conditions_patients', 'condition_id', 'patient_id');
    }
}
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Condition extends Model
{
    protected $table = 'medical_conditions';
}
factory(Patient::class, 10)->create()->each(function ($p) {
    $p->conditions->sync(App\Condition::class)->make();
});

Please sign in or create an account to participate in this conversation.