0

I have following pivot table.

+----+-----------+-----------+
| id | tableA_id | tableB_id |
+----+-----------+-----------+
|  1 |         1 |         1 |
|  2 |         1 |         2 |
|  3 |         1 |         3 |
|  4 |         2 |         1 |
|  5 |         2 |         4 |
+----+-----------+-----------+

Controller:

$tableAs = \App\TableA::all();

Many to many relation are already defined in the model, and view code is following.

@foreach ($tableAs as $tableA)
@foreach ($tableA->$tableBs as $tableB)
<p>{{ $tableA->id . ' - ' . $tableB->id }}</p>
@endforeach
@endforeach

Now, I want to get distinct rows for table B.
If above table, the current output is:

1 - 1
1 - 2
1 - 3
2 - 1 // <- not expect
2 - 4

What is the best practice to achieve my hope without writing logic in the view file?

tk-aporo
  • 1
  • 1
  • 1
    Is `2-1` not expected because `1-2` already exists? You could make sure beforehand that those "unexpected" relations don't get saved in the database – brombeer Nov 19 '19 at 14:13
  • The best way is like @kerbholz said, you don't need to saved the same records in your pivot table.Unless you have anther column, and that column is different message. However, if that column exists, you need to put it in tableA or tableB. – TsaiKoga Nov 19 '19 at 14:29
  • I third @kerbholz suggestions, but if you must, do have a look at this post for ideas: https://stackoverflow.com/questions/55633472/belongstomany-relation-how-to-get-unique-rows – user3532758 Nov 19 '19 at 14:34
  • Yes. But in other cases, need to get both `1-2` and `2-1`, so both records need to be saved. By the way, there are other columns in the pivot table. @kerbholz – tk-aporo Nov 19 '19 at 15:31

1 Answers1

0

can you please try with this code

$tableAs = \App\TableA::distinct('tableB_id')->all();

Suraj15689
  • 29
  • 4