簡體   English   中英

未定義的屬性:Illuminate \\ Database \\ Eloquent \\ Collection :: Laravel 5.2

[英]Undefined property: Illuminate\Database\Eloquent\Collection:: Laravel 5.2

我試圖讓物聯網顯示訂單中的項目,但我不斷收到此錯誤

這些是我的模特

class westcoorder extends Model
{
    protected $table = 'westcoorders';
    protected $with = 'westcoorderitem';

    protected $fillable = ['is_sent', 'is_delivered'];

    /**
    * @return \Illuminate\Database\Eloquent\Relations\HasMany
    */
    public function westcoorderitem()
    {
        return $this->hasMany('App\westcoorderitem');
    }
}

class westcoorderitem extends Model
{
    protected $table = 'westcoorderitems';

    protected $fillable = ['westcoorder_id','quantity', 'productName', 'productCode', 'price'];


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

這是我的控制器

public function onGoingOrder($orderNumber)
{
    $orderNumber = westcoorder::where('id', $orderNumber)->firstOrFail();

    $items = westcoorderitem::where('westcoorder_id', $orderNumber)->get();

    return view('westco.onGoingOrder', compact('orderNumber', 'items'));
}

這就是我的看法

<div class="panel-heading">Order @if ($orderNumber) {{ $orderNumber->id }} @endif Items</div>
        <div class="panel-body">
                @if($items)
                        {{ $items->productName }}
                @endif
        </div>

這是我的桌子的樣子

Schema::create('westcoorders', function (Blueprint $table)
{
        $table->increments('id');
        $table->tinyInteger('is_sent')->default(0);
        $table->tinyInteger('is_delivered')->default(0);
        $table->timestamps();
} );

Schema::create('westcoorderitems', function (Blueprint $table)
{
        $table->increments('id');
        $table->Integer('westcoorder_id'); // fk for westcoOrder.id
        $table->string('quantity');
        $table->string('productName');
        $table->string('productCode');
        $table->decimal('price');
        $table->timestamps();
} );

這是我得到的錯誤

Undefined property: Illuminate\Database\Eloquent\Collection::$productName

像您的錯誤狀態:

未定義的屬性:Illuminate \\ Database \\ Eloquent \\ Collection :: $ productName

您正在嘗試訪問集合中的屬性,而不是模型。 首先,您可以利用創建的關系,如下所示:

$order = App\westcoorder::where('id', $orderNumber)->with('westcoorderitem')->firstOrFail();

這將確保訂單商品將包含在結果中,而不是執行另一個查詢來獲取它們。

然后,您可以將$order傳遞給視圖:

return view('welcome', compact('orderNumber', 'order'));

(您也可以只刪除實際訂單的orderNumber)

然后,您可以在視圖中訪問order並遍歷以下items

@foreach($order->westcoorderitem as $item)
    {{ $item->productName }}
@endforeach

FK

另一個提示可能是更新表以使用索引來提高性能並使表整潔,就像您在create migration的注釋中提到的FK一樣。 您可以進行遷移以對其進行更新,例如:

$table->foreign('westcoorder_id')->references('id')->on('westcoorders');

和/或根據您的需求(級聯等)對此進行擴展。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM