首页 > 解决方案 > 我有两个表,它们有一对多的关系,我正在尝试通过 id 从两个表中检索数据

问题描述

供应商模式

public function supplierlandlines(){
        return $this->HasMany('\App\Supplierlandline');
     }

供应商座机模型

public function suppliers(){
        return $this->BelongsTo('\App\Supplier');
     }

控制器

public function show (){
        $suppliers=\App\Supplier::all();
        $supplierlandlines = \App\Supplier::find(1)->supplierlandlines;


    return view('suppliers',compact('suppliers','supplierlandlines'));




    }

看法

@foreach($suppliers as $supplier)
                            <tr >


                                <td >{{$supplier->name}}</td>
                                <td >{{$supplier->company}}</td>
                                <td >{{$supplier->address}}</td>
                                <td >{{$supplier->email}}</td>

                                    <ul >
                                        @foreach($supplierlandlines as $supplierlandline)

                                        <li>{{$supplierlandline->landline}}</li>

                                        @endforeach

                                    </ul>
                                </td>

                          </tr>

这将为所有供应商返回第一个供应商的座机,我需要为每个供应商返回座机

标签: mysqllaravel

解决方案


尝试使用急切加载

控制器:

public function show (){
   $suppliers = \App\Supplier::with('supplierlandlines')->all();

    return view('suppliers', ['suppliers' => $suppliers]);
}

看法:

@foreach($suppliers as $supplier)
    <tr >
        <td >{{$supplier->name}}</td>
        <td >{{$supplier->company}}</td>
        <td >{{$supplier->address}}</td>
        <td >{{$supplier->email}}</td>
            <ul >
                @foreach($supplier->supplierlandlines as $supplierlandline)
                    <li>{{$supplierlandline->landline}}</li>
                @endforeach
            </ul>
        </td>
    </tr>
@endforeach

推荐阅读