ethump's avatar
Level 1

Multi-column relationships

Struggling with this one so reaching out to the hive mind!

I have a table 'stuff' that looks like this:

id set index text
1 A 1 Some A1 text
2 A 2 Some A2 text
3 A 3 Some A3 text
4 B 1 Some B1 text
5 B 2 Some B2 text
6 B 3 Some B3 text
7 B 4 Some B4 text
8 B 5 Some B5 text
9 C 1 Some C1 text
10 C 2 Some C2 text

And I have another table 'things' that looks like this:

id set index active status
1 A 1 1 Green
2 A 2 1 Blue
3 A 3 0 Yellow
4 B 1 1 Green
5 B 3 0 Blue
6 B 5 0 Purple

What I want to do is for a give input on 'things' for instance set=B, loop through 'stuff' and pull out the corresponding text.

$result=Things::where('set','B')->some incantation->get();

where $result will be like:

set index text active status
B 1 Some B1 text 1 Green
B 3 Some B3 text 0 Blue
B 5 Some B5 text 0 Purple

The plan is that I'll then link $result into an HTML table with some Livewire goodness to manipulate 'active' and 'status' fields back in the 'stuff' table.

Using Lara 11.latest - Yes, I know I need to be looking at Eloquent relationships but I'm struggling matching on the non-native ID column.

Cheers all, and seasons greetings!

0 likes
5 replies
Tray2's avatar

I'm not sure if you can define a multi-column relationship in Eloquent, but with regular SQL it's pretty simple.

SELECT
  s.last_name, s.first_name,
  p.course_code, p.status, p.amount
FROM enrollment e
JOIN student s
  ON s.id=e.student_id
JOIN payment p
  ON p.course_code=e.course_code
    AND p.student_id=e.student_id;

https://learnsql.com/cookbook/how-to-join-on-multiple-columns/

ethump's avatar
Level 1

cheers, yeah was hoping not to resort to SQL.. but I know it's an option.

jlrdw's avatar

@ethump

yeah was hoping not to resort to SQL..

Eloquent converts to regular sql at runtime anyway. It's not a language.

Please or to participate in this conversation.