Laravel反向关系

时间:2017-05-21 17:39:25

标签: php sql laravel controller

所以我有两张桌子:

Schema::create('goods', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->integer('amount');
            $table->integer('shop_id');
            $table->timestamp('onPurchase');
            $table->timestamps();
        });

Schema::create('shops', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('adress')->nullable();
            $table->timestamps();
        });

我想打印所有商品的清单,并在商品的每一行添加商店的名称。当路线打开时,此功能运行:

function toBuy(){
        $good = Good::all();
        $data ['good'] = $good;
        return view('tobuy', $data);
    }

刀片:

@foreach ($good as $ginfo)
                <tr>
                    <td>{{$ginfo->name}}</td>
                    <td>{{$ginfo->amount}}</td>
                    <td>
                    @foreach ($ginfo->shop as $shop)
                        {{$shop->name}}
                    @endforeach
                    </td>
                    <td>
                    <a href="{{ route ('goodDelete', $ginfo->id) }}" type="submit" class="btn btn-default">Delete</a>
                    </td>
                </tr>
                @endforeach

那么我如何使用模型Good和Shop形成一个正确的关系并打印我需要的东西。试过很多方法但都失败了。请帮忙。

1 个答案:

答案 0 :(得分:1)

将此添加到您的Good型号

public function shop()
{
    return $this->belongsTo('App\Shop');
}

控制器代码

public function toBuy()
{
    $goods = Good::with('shop')->get();

    return view('tobuy')->with(['goods' => $goods]);
}

查看代码

@foreach ($goods as $good)
    <tr>
        <td>{{ $good->name }}</td>
        <td>{{ $good->amount }}</td>
        <td>{{ $good->shop->name }}</td>
        <td>
            <a href="{{ route ('goodDelete', $good->id) }}" type="submit" class="btn btn-default">Delete</a>
        </td>
    </tr>
@endforeach