首页 > 解决方案 > 视图中外键列中字段的回显值

问题描述

请注意:我是 Laravel 的新手,对一般编程很陌生

因此,我试图在我的订单索引中的“客户”和“用户”表中回显该字段的值,其中我有一个所有订单的列表,但我不断收到错误“尝试获取属性“名称”非对象'

订单控制器

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Order;

class OrderController extends Controller
{
    public function __construct()
    {
        $this->middleware('auth');
    }

    public function index()
    {
        $orders = Order::all();
        $orders = Order::orderBy('updated_at', 'asc')->paginate(10);
        $orderCount = Order::count();
        return view('orders.index',[
            'orders'=> $orders,
            'orderCount' => $orderCount
            ]);
    }
}

订购型号

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
    public function users()
    {
        return $this->belongsTo('App\User');
    }

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

    public function products()
    {
        return $this->belongsToMany('App\Product');
    }
}

用户模型

<?php

namespace App;

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use Notifiable;

    protected $fillable = [
        'name', 'email', 'password', 'roles_id'
    ];

    protected $hidden = [
        'password', 'remember_token',
    ];

    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    public function roles()
    {
        return $this->belongsToMany('App\Role');
    }

    public function orders()
    {
        return $this->hasMany('App\Order');
    }

    public function authorizeRoles($roles)
    {
        if (is_array($roles)) {
            return $this->hasAnyRole($roles) || 
                    abort(401, 'This action is unauthorized.');
        }
        return $this->hasRole($roles) || 
                abort(401, 'This action is unauthorized.');
    }
    /**
    * Check multiple roles
    * @param array $roles
    */
    public function hasAnyRole($roles)
    {
        return null !== $this->roles()->whereIn('name', $roles)->first();
    }
    /**
    * Check one role
    * @param string $role
    */
    public function hasRole($role)
    {
        return null !== $this->roles()->where('name', $role)->first();
    }
}

客户模型

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Customer extends Model
{
    public function orders()
    {
        return $this->hasMany('App\Order');
    }
}

orders.index 刀片

@extends('layouts/app')

@section('content')

<div class="row">
        <div class="col-md-12">
            <div class="card">
                <div class="card-header">
                    <h4>Orders</h4>
                </div>

                <div class="panel-body">
                    @if (count($orders) > 0)
                    <table class="table">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>Recieved on</th>
                                <th>Customer</th>
                                <th>Worker</th>
                                <th>Price</th>
                            </tr>
                        </thead>
                    @foreach ($orders as $order)
                        <tr>
                            <tbody>
                                <td>#{{$order->id}}</td>
                                <td>{{$order->created_at}}</td>
                                <td>{{$order->customers->name}}</td>
                                <td>{{$order->users->name}}</td>
                                <td>${{$order->total_price}}</td>
                                <td><a href="/orders/{{$order->id}}/edit" class="btn btn-primary btn-sm"><i class="fas fa-edit"></i></a></td> 
                                <td>
                                    <span class="table-remove">
                                         {!!Form::open(['action' =>['OrderController@destroy', $order->id], 'method' => 'POST'])!!}
                                            {{Form::hidden('_method', 'DELETE')}}
                                            {{ Form::button('<i class="fas fa-trash-alt" aria-hidden="true"></i>', ['class' => 'btn btn-danger btn-sm', 'type' => 'submit']) }}
                                        {!!Form::close()!!}
                                    </span>
                                </td>                               
                        </tr>
                    @endforeach
                    @if ($orderCount > 9)
                    <tr>
                        <td>{{$orders->links()}}</td>
                    </tr>
                    @endif
                </tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
@else
    <p>No orders found</p>

@endif

@endsection

创建订单表

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateOrdersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('orders', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->enum('status', ['Not started', 'In progress', 'Completed']);
            $table->text('notes');
            $table->string('rs_login');
            $table->string('rs_password');
            $table->double('total_price', 10, 2);
            $table->unsignedBigInteger('customer_id')->index();
            $table->foreign('customer_id')->references('id')->on('customers');
            $table->unsignedBigInteger('user_id')->index()->nullable();
            $table->foreign('user_id')->references('id')->on('users');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('orders');
    }
}

所以我的问题是,如何在我的“订单”表中回显由 id 表示的用户和客户名称

标签: laravel

解决方案


通过将我的订单模型更改为:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
    public function users()
    {
        return $this->belongsTo('App\User', 'user_id');
    }

    public function customers()
    {
        return $this->belongsTo('App\Customer', 'customer_id');
    }

    public function product()
    {
        return $this->belongsToMany('App\Product');
    }
}

推荐阅读