【问题标题】:Laravel inverse relationLaravel 逆关系
【发布时间】:2017-10-21 08:17:47
【问题描述】:

所以我有两张桌子:

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 建立适当的关系并打印我需要的东西。尝试了很多方法,都失败了。请帮忙。

【问题讨论】:

    标签: php sql laravel controller


    【解决方案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
    

    【讨论】:

    • 我得到:Builder.php 第 2451 行中的 BadMethodCallException:调用未定义的方法 Illuminate\Database\Query\Builder::all()
    • @Benua 对此感到抱歉,已更新。忘记用get()替换all()
    猜你喜欢
    • 1970-01-01
    • 2021-12-11
    • 2016-02-29
    • 1970-01-01
    • 1970-01-01
    • 2021-06-30
    • 1970-01-01
    • 2017-07-16
    • 2011-07-31
    相关资源
    最近更新 更多