Search code examples
laravellaravel-7

Laravel 7 Relationship many to many not working


An event can be in one to several years and a year can have several events, hence the use of the many-to-many relationship.

So I have 3 tables: evenements, years and evenement_year (pivot table).

I carefully read the Laravel 7 documentation and thought I had followed the procedure :

Evenement Model :

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Evenement extends Model
{
    protected $fillable = ['name', 'year_id','mnemonique','color'];

    //One yar can have severals events and I give the name events_years to pivot
    public function years()
    {
        return $this->belongsToMany(Year::class, 'evenement_year'); 
    }
}

Year Model :

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Year extends Model
{
    protected $fillable = ['name'];

    public function evenements()
    {

        // a event can be in several years and I give the name events_years to pivot
        return $this->belongsToMany(Evenemnt::class, 'evenement_year');
        
    }
}

When I try to SELECT all events with years with this code (in the EventementController) at the index method :

<?php

namespace App\Http\Controllers;

use App\Evenement;
use App\EvenementType;
use App\Type;
use App\Year;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use stdClass;

class EvenementController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
    }

    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $evenements = Evenement::orderBy('year_id')->orderBy('mnemonique')->get();
        $years = Year::all();
        $evenTypes= EvenementType::all();
        $types= Type::All();


        return view('evenement.index', compact('evenements', 'years','evenTypes','types'));
    }


}

I have this error :

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'year_id' in 'order clause' (SQL: select * from evenements order by year_id asc, mnemonique asc)

Thank you for your help and have a nice Sunday.

Edit :

This is the view code :

@extends('adminlte::page')
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/spectrum-colorpicker2/dist/spectrum.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/spectrum-colorpicker2/dist/spectrum.min.css">

@section('title', 'Cours')

@section('content_header')
<h1>Liste des évènements</h1>
@stop

@section('content')
<p>La liste de tous les évènements enregistrer</p>

<div class="card">
    <div class="card-header">
        <a href="{{ route('evenement.create') }}" class="btn btn-sm btn-primary">Ajouter un événement</a>
            
    </div>

    <div class="filtre">
    <p margin:50>Selectionner une année <br>
    <SELECT name="filtreAnnée" margin: 50>
            <libellé>Selectionner une année</libellé>
            <option valeur="tout">Toutes les années</option>
            <option valeur="BA1">BA1</option>
            <option valeur="BA2">BA2</option>
            <option valeur="BA3">BA3</option>
            <option valeur="MA1">MA1</option>
            <option valeur="MA2">MA2</option>
            </SELECT>
    </div>

    <div class="card-body">
        <div class="table-responsive">
            <table class="table table-hover">
                <thead>
                    <tr>
                        <th>Mnémonique</th>
                        <th>Nom</th>
                        <th>Année</th>
                        <th>Couleur</th>
                        <th>Action</th>
                    </tr>
                </thead>
                <tbody>
                    @foreach ($evenements as $evenement)
                    <tr style="outline: thin solid">
                        <td>{{ $evenement->mnemonique }}</td>
                        <td>{{ $evenement->name }}</td>
                        <td>{{ $evenement->year->name }}</td>
                        <td>{{ $evenement->color}}</td>
                        <td>
                            <button type="button" class="btn btn-sm btn-warning" id="edit" data-toggle="modal" data-target="#edit-modal-{{ $evenement->id }}">
                                <i class="far fa-edit"></i>
                            </button>

                            @include('evenement.update')

                            <button type="button" class="btn btn-sm btn-danger" data-toggle="modal" data-target="#delete-modal-{{ $evenement->id }}">
                                <i class="far fa-trash-alt"></i>
                            </button>

                            @include('evenement.delete')

                        </td>
                    </tr>
                       <?php $displayTh = false ?>
                        @foreach ($evenTypes as $evenT)

                                @if (!$displayTh)
                                    <?php $displayTh=true ?>
                                    <tr>
                                        <th>              </th>
                                        <th>Type de cours </th>
                                        <th>Nombre d'heure</th>
                                        <th>
                                            <button  type="button" class= "btn btn-sm btn-primary" data-toggle="modal" data-target="#create-type-modal-{{ $evenement->id }}">
                                                <i class="fa fa-plus-circle" aria-hidden="true"></i>
                                            </button>

                                            @include('evenement.createEvenementType')
                                        </th>
                                    </tr>
                                @endif

                            @if ($evenement->id == $evenT->evenement_id )

                                <tr>
                                    <td>      </td>
                                    <td>{{$evenT->type->name}}</td>
                                    <td>{{$evenT->total_hours}}</td>
                                    <td><button type="button" class="btn btn-sm btn-danger" data-toggle="modal" data-target="#delete-type-modal-{{ $evenT->id }}">
                                        <i class="fas fa-minus-circle"></i>
                                    </button>
                                    @include('evenement.deleteEvenementType')
                                </td>

                                </tr>

                            @endif
                        @endforeach


                        <tr></tr>
                    @endforeach
                    <script>
                        $(".basic").spectrum();
                    </script><!-- palette de couleur-->
                </tbody>

            </table>
        </div>

    </div>
</div>
@stop

@section('css')
@stop

@section('js')
@stop

edit 2 (dd to array)

I need name from array62 and name from array 5 for example.

array:62 [▼   

0 => array:7 [▼

"id" => 61
"name" => "Accueil"
"mnemonique" => "Accueil"
"color" => "#bcbcbc"
"created_at" => "2021-07-13T14:16:04.000000Z"
"updated_at" => null
"years" => array:2 [▼
  0 => array:5 [▼
    "id" => 1
    "name" => "BA1"
    "created_at" => "2021-07-13T14:16:04.000000Z"
    "updated_at" => null
    "pivot" => array:2 [▶]
  ]
  1 => array:5 [▼
    "id" => 4
    "name" => "MA1"
    "created_at" => "2021-07-13T14:16:04.000000Z"
    "updated_at" => null
    "pivot" => array:2 [▶]
  ]
]   ]

Solution

  • using with we can order by related data

    For Ascending order

    $evenements = Evenement::with(['years'=>function ($query){
                         $query->orderBy('year_id');
                  }])->get();
    

    For Descending order

     $evenements = Evenement::with(['years'=>function ($query){
                             $query->orderByDesc('year_id');
                      }])->get();
    

    For retrieving those Evenement which has years then

     $evenements = Evenement::with(['years'=>function ($query){
                                 $query->orderByDesc('year_id');
                          }])->has('years')->get();
    

    To get related table columns if its in blade file then

    @foeach($evenements as $event)
     
      @if(isset($event->years)&&count((array)$event->years))
        @foreach($event->years as $year)
    
          {{$year->name??null}}
        @endforeach
      @endif
     
    @endforeach