ictoplossing's avatar

How to retrieve data from related table in model?

Hello, I create an appointments system:

  1. Create some Contact: name, phone, and multiple select of addresses from a module Address.
  2. Create an Appointment where can select created contact from the first step.

All relations of Contact with Addresses are stored in a model PersonAddress, table "person_address" (columns: id, person_id, address_id).

Now i can retrieve only list (json):

{
	"id": 60,
	"title": "test",
	"assigned_with_person_id": 261,
	"persons_addresses": [
		{
			"id": 227,
			"person_id": 261,
			"address_id": 54
		},
		{
			"id": 228,
			"person_id": 261,
			"address_id": 52
		},
		{
			"id": 229,
			"person_id": 261,
			"address_id": 100
		}
	],
}

where "address_id" is foreign key with the table "addresses".

There my code:

Appointment model (table "appointments"):

    public function personsAddresses()
    {
        return $this->hasMany(
            PersonAddress::class,
            'person_id',
            'assigned_with_person_id'
        );
    }

then i call in AppointmentController:

public function returnAppointment(Request $request, $id)
    {
        $appointments = Appointment::where('id', $id)
            ->with([
                'personsAddresses',
            ])
            ->first();
        return Response::json($appointments, 200);
    }

How to retrieve all fields (title, street, nr., phone) from the table "addresses" (by id) via related table "person_addresses" and show them in founded Appointment?

I have tried to read Laravel docs but i can't understand this :)

0 likes
2 replies
tisuchi's avatar
tisuchi
Best Answer
Level 70

@ictoplossing Try this:

public function addresses()
{
    return $this->hasManyThrough(
        Address::class,
        PersonAddress::class,
        'person_id',
        'id',
        'assigned_with_person_id',
        'address_id'
    );
}
public function returnAppointment(Request $request, $id)
{
    $appointments = Appointment::where('id', $id)
        ->with([
            'personsAddresses',
            'addresses',
        ])
        ->first();
    return Response::json($appointments, 200);
}
2 likes

Please or to participate in this conversation.