数据透视表选择LARAVEL

时间:2020-01-10 14:21:57

标签: php laravel pivot pivot-table laravel-blade

我有这个问题,我需要通过数据透视表中的id来了解某个模式的完整性,但这会返回给我:

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 :(得分:0)

因此,根据注释,您的表如下所示:

+--------+  +--------------+  +------------------------------+
|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:在belongsToManyFiliere模型之间添加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
相关问题