DEV Community

drnwork
drnwork

Posted on

How to create associative table in laravel?

I want to create associative table , I have Many to Many relationship between L_Examen_Categorie and L_Examen_SousCategorie. My associative table named L_Examen_Categorie_Souscategorie where i am going to insert id_categorie and id_soucsategorie .

By the way I am getting the data from other tables P_Examen_Categorie and P_Examen_SousCategorie

Here is it my code:

$categorie = DB::table('P_Examen_Categorie as p')

            ->where('p.id_examen', '=', $id_examen)
->get();
    foreach ($categorie as $cat_item) {

        $l_cat_item = array(
            'code' => $cat_item->code,
            'libelle' => $cat_item->libelle,
            'id_examen' => $cat_item->id_examen,
            'Note' => $cat_item->Note,
            'coefficient' => $cat_item->coefficient,
            'id_lexamen' => $id
        );
        L_Examen_Categorie::insert($l_cat_item);
        $idcat=L_Examen_Categorie::get('id');
            $cat_item = DB::table('P_Examen_SousCategorie as p')
                ->select('id', 'code', 'id_categorie', 'libelle', 'Note', 'coefficient')
                ->where('p.id_categorie', '=', $cat_item->id)
                ->get();


            foreach ($cat_item as $item) {
                $l_souscat_item = array(
                    'code' => $item->code,
                    'libelle' => $item->libelle,
                    'Note' => $item->Note,
                    'coefficient' => $item->coefficient,
                    'id_categorie' => $item->id_categorie,
                );
                L_Examen_SousCategorie::insert((array)$l_souscat_item);
                $model = array(
                    'id_categorie' =>$cat_item->id,
                    'id_souscategorie' =>$item->id,
                );
                L_Examen_Categorie_Souscategorie::insert($model);
            }
    } 
Enter fullscreen mode Exit fullscreen mode
Enter fullscreen mode Exit fullscreen mode




Laravel #php

Top comments (0)