将订单 ID 与用户 ID 关联并获取用户名 Laravel 7

我正在尝试根据卖家 ID 获取用户创建的报价的用户名。我在数据库中有 2 个表:第一个表 User


用户
|
| - 身份证
| - 姓名

第二个表订单:


订单
|
| - 身份证
| - 卖家(用户 ID)

我想要实现的是根据订单的卖家 ID 获取用户名
这是我的 Controller.php:

<?php


namespace App\Http\Controllers;


use Illuminate\Http\Request;

use Illuminate\Support\Facades\DB;

Use Auth;

Use App\User;

use Illuminate\Support\Facades\Validator;

use Session;


class MarketplaceController extends Controller


public function index(){


        $offers = DB::table('order')->paginate(30);


        return view(

            'marketplace.index',

            [

                'title'              => 'Browse offers',

                'offers'             => $offers,

            ]

        );


    }

}

这是我的blade.php


       @foreach($offers as $offer)

                <hr>


                <div data-link="/offer/{{ $offer->id }}" class="col-12 offer">

                    <div class="col-3">{{ $offer->title }}</div>

                    <div class="col-3">{{ $offer->description }}</div>

                    <div class="col-3">{{ $offer->status }}</div>

                    <div class="col-1">{{ $offer->price }}zł</div>

                    <div class="col-2">Sprzedawca:{{ $offer->seller }}</div>

                </div>

        @endforeach


        <div class="col-6 offset-3" id="pagination">


            {{ $offers->links() }}

        

        </div>

我正在使用 Laravel 7.21.0 你有什么想法吗?


慕无忌1623718
浏览 108回答 2
2回答

素胚勾勒不出你

在您的Order模型中,您将添加public function seller() {&nbsp; &nbsp; return $this->belongsTo(User::class, 'seller');}&nbsp;在您看来,您将使用seller()关系来访问User模型数据@foreach($offers as $offer)&nbsp; &nbsp; &nbsp; ...&nbsp; &nbsp; &nbsp; <div class="col-2">Sprzedawca:{{ $offer->seller->name }}</div>&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp; &nbsp; &nbsp; ...@endforeach

胡说叔叔

在函数索引中使用表 User 和 Orders 之间的链接尝试以下操作:public function index(){&nbsp; &nbsp; $offers = DB::table('order')&nbsp; &nbsp; &nbsp;->join('users','user.id','=','order.seller ')&nbsp; &nbsp; &nbsp; ->select('user.name','order.*')&nbsp; &nbsp; &nbsp; ->paginate(30);&nbsp; &nbsp; return view('marketplace.index',&nbsp; &nbsp; &nbsp; &nbsp; [&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'title'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; => 'Browse offers',&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'offers'&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;=> $offers,&nbsp; &nbsp; &nbsp; &nbsp; ]&nbsp; &nbsp; );&nbsp; }
打开App,查看更多内容
随时随地看视频慕课网APP