How to create a relationship between 3 tables Laravel?

1

I have 3 tables that you need to join to access the information. By the relation of Laravel I can create simple relations, such as belongsTo .

I'm trying to access the information from the first table with the id of the third table. In case, by the id of the table_days_timebook I want to search the patient's name.

pessoas
  -- id
  -- nome

pacientes
  -- id
  -- id_pessoa

agenda_dias
  -- id
  -- id_paciente

In Person Model I created the following function:

public function agendaDiaPaciente() 
{
    return $this->hasManyThrough(
                    'Models\AgendaDia', 'App\Models\Paciente',
                    'pessoa',           'id_paciente',         'id'
    )
}

Patient Model:

    public function pessoa()
{
    // Cria vinculo com tabela de pessoas. Inverso de hasOne();
    return $this->belongsTo('App\Models\Pessoa', 'id_pessoa');
}

DayDay Model:

public function paciente() 
{
    return $this->belongsTo('App\Models\Paciente', 'id_paciente');
}
    
asked by anonymous 03.06.2017 / 14:27

1 answer

3

I will only worry about relationships, they are a bit strange, but, by the description would be this:

namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Pessoas extends Model
{
    public function paciente()
    {
        return $this->hasOne('App\Models\Pacientes', 'id_pessoa', 'id');
    }
}
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Pacientes extends Model
{
    public function pessoa()
    {
        return $this->belongsTo('App\Models\Pessoas', 'id_pessoa', 'id');
    }

    public function agendadias()
    {
       return $this->hasOne('App\Models\AgendaDias', 'id_paciente', 'id');
    }
}
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class AgendaDias extends Model
{
    public function paciente()
    {
        return $this->belongsTo('App\Models\Pacientes', 'id_paciente', 'id');
    }
}

Search:

$c = App\Models\AgendaDias::find(1)->paciente()->first()->pessoa()->first();

echo $c->nome;
    
03.06.2017 / 14:41