Выбор сводной таблицы LARAVEL - PullRequest
1 голос
/ 10 января 2020

У меня есть эта проблема, мне нужно иметь встроенный режим с помощью идентификаторов в сводной таблице, но он возвращает мне это:

Объект класса stdClass не может быть преобразован в строку

Вот мой контроллер

$filiere = Filiere::all();
$fcount =  count($filiere);
$filiere22 = DB::select('select id from filiere');
foreach ($filiere22 as $filiere2 ){
    $md = DB::select('select intitule from mode_formation where id in(SELECT mode_id from mode_filiere where filiere_id='.$filiere2.')');
} return view('pgsec',compact('md','ssec','s_secteur','filiere','secteur','sec','secteur2','niveau','niv','province','pr','fcount','region','r','op','operateur'));

и вот мой клинок

@foreach($filiere as $f)
    <tr class="item{{$f->id}}">
        <td style="font-size: 13px;">
            <a href="f/{{$f->id}}">{{$f->intitule}}</a> 
        </td>
        @foreach($md as $m)
            <td style="font-size: 13px;">{{$m->intitule}}</td>
        @endforeach
    </tr>
@endforeach

1 Ответ

0 голосов
/ 13 января 2020

Итак, согласно комментариям, ваши таблицы выглядят так:

+--------+  +--------------+  +------------------------------+
|filiere |  |mode_formation|  |mode_filiere                  |
+--------+  +--------------+  +------------------------------+
|id (pk) |  |id (pk)       |  |filiere_id (fk to filiere)    |
|intitule|  |intitule      |  |mode_id (fk to mode_formation)|
+--------+  +--------------+  +------------------------------+

Исходя из этого и вашего кода, я предполагаю следующее:

  • Filiere В модели используется таблица filiere.
  • Для таблицы mode_formation нет модели.
  • Модель для таблицы mode_filiere отсутствует.

Шаг 1: Создайте модель для таблицы mode_formation.

  1. Запустите команду php artisan make:model ModeFormation
  2. Просто, чтобы убедиться, отредактируйте файл модели (по умолчанию расположен в app/ModeFormation.php ), чтобы добавить таблицу, которую она представляет.

Шаг 2: Добавить belongsToMany отношение между Filiere и ModeFormation моделями

Шаг 3: Использовать eager loading в вашем контроллер, чтобы избежать выполнения стольких запросов

Шаг 4: Используйте отношения в своем представлении

В конце ваши модели должны выглядеть следующим образом:

# app/Filiere.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Filiere extends Model
{
    protected $table = 'filiere';

    public function mode_formations()
    {
        return $this->belongsToMany(ModeFormation::class, 'mode_filiere', 'filiere_id', 'mode_id');
    }
}
# app/ModeFormation.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class ModeFormation extends Model
{
    protected $table = 'mode_formation';

    public function filieres()
    {
        return $this->belongsToMany(Filiere::class, 'mode_filiere', 'mode_id', 'filiere_id');
    }
}

Эта часть в вашем контроллере должна выглядеть так:

// you only need this one variable for what you're trying to accomplish
$filieres = Filiere::with('mode_formations')->get();

И ваш взгляд:

@foreach($filieres as $filiere)
    <tr class="item{{ $filiere->id }}">
        <td style="font-size: 13px;">
            <a href="f/{{ $filiere->id }}">{{ $filiere->intitule }}</a> 
        </td>
        @foreach($filiere->mode_formations as $mode_formation)
            <td style="font-size: 13px;">{{ $mode_formation->intitule }}</td>
        @endforeach
    </tr>
@endforeach
...