Romentigo
4 months ago
306
2
Laravel

Get value through few relations

Posted 4 months ago by Romentigo

I have Pairs table. Model Pair belongsTo Classroom model, Classroom model belongsTo Campus model.

Pairs table:

  • id
  • classroom_id
  • ...

Classrooms table:

  • id
  • number
  • campus_id
  • ...

Campuses table:

  • id
  • name

In my Pairs table I can get Classroom's number, but I need to get somehow Campus name value right into Pairs table. With this code I get everything except campus name, only it's id:

$pairs = Pair::with('group', 'subject', 'lecturer', 'day', 'pairNumber', 'pairType', 'classroom', 'week')
            ->where('group_id', '=', $id)
            ->orderBy('day_id', 'ASC')
            ->orderBy('pair_number_id', 'ASC')
            ->get();

When I request pairs, I can see in JSON response that classroom are send as object with it's own values. But I want to insert campus object inside classroom object to get Campus name value by relations. I know that I haven't pointed Campuses relation in Pair::with, but if I do that, an exception will be thrown because of unknown relation. That what I get now in response, only campus_id:

[{id: 1, classroom_id: 14, subject_id: 3, lecturer_id: 3, group_id: 14, day_id: 1, week_id: 2,…}]
0: {id: 1, classroom_id: 14, subject_id: 3, lecturer_id: 3, group_id: 14, day_id: 1, week_id: 2,…}
classroom: {id: 14, number: 201, campus_id: 2, classroom_type_id: 1, department_id: 3,…}
campus_id: 2
classroom_type_id: 1
created_at: "2020-06-08T10:05:02.000000Z"
department_id: 3
id: 14
number: 201
updated_at: "2020-06-08T10:05:02.000000Z"
classroom_id: 14
created_at: "2020-06-08T11:10:54.000000Z"
...

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