0

For example, I have some models and related tables, they are :

  1. Permohonan (table name: peminjam)

    • id
    • nama_lengkap
  2. Klasifikasi

    • id
    • penerima_id
    • kriteria_id
    • sub_kriteria_id
  3. kriteria

    • id
    • nama_kriteria
  4. SubKriteria (table name: sub_kriteria)

    • id
    • nama_sub_kriteria
    • bobot

they are well connected, but I want create an array that holds relationship data from the klasifikasi table.

this is the content of klasifikasi table :

| id | peminjam_id | kriteria_id | sub_kriteria_id |
| 72 | 16          | 1           | 12              |
| 73 | 16          | 2           | 7               |
| 74 | 16          | 3           | 13              |
| 75 | 17          | 1           | 14              |
| 76 | 17          | 2           | 6               |
| 77 | 17          | 3           | 20              |

Oke, and this is my php code in Controller :

public function index()
    {
        $q = Permohonan::all();
        foreach($q as $peminjam){
            $cls = Permohonan::find($peminjam->id);
            foreach($cls->kriteria as $kriteria){
                $kriteriaID[$peminjam->id][$kriteria->id] = "sub_kriteria_id";
            }
        }

        echo '<pre>';
        print_r($kriteriaID);
    }

output :

Array
(
    [16] => Array
        (
            [1] => sub_kriteria_id
            [2] => sub_kriteria_id
            [3] => sub_kriteria_id
        )

    [17] => Array
        (
            [1] => sub_kriteria_id
            [2] => sub_kriteria_id
            [3] => sub_kriteria_id
        )
)

in the second array, can I put id instead of sub_kriteria table into array value? so the output is as follows like this :

Array
    (
        [16] => Array
            (
                [1] => 12
                [2] => 7
                [3] => 13
            )

        [17] => Array
            (
                [1] => 14
                [2] => 6
                [3] => 20
            )
    )

I hope any body can help me to solve this case. Thank you..

1

1 Answer 1

0

Laravel relationship is the best way to achieve your desired result: https://laravel.com/docs/6.x/eloquent-relationships

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.