簡體   English   中英

Laravel 5.4 hasManyToTo不能正常工作

[英]Laravel 5.4 hasMany belongsTo not working

我正在嘗試在Blade foreach語句中引用關系

@foreach($customer->invoices as $invoice)

我收到的錯誤是Undefined property: stdClass::$invoices (View: ...\\customerView.blade.php)

這是客戶和發票模型的代碼

顧客

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

發票

class Invoice extends Model
{
   public function customer()
   {
      $this->belongsTo('App\Customer');
   }
}

這是這兩個數據庫的遷移文件。

顧客

Schema::create('customers', function (Blueprint $table) {
   $table->increments('id');
   $table->string('firstName');
   $table->string('lastName');
   $table->string('phoneNumber');
   $table->string('email');
});

發票

Schema::create('invoices', function (Blueprint $table) {
   $table->increments('id');
   $table->integer('customer_id');
   $table->integer('item_id');
   $table->date('dateCreated');
   $table->string('balance');
   $table->string('status');
});

有人能夠看到我所缺少的嗎?

關聯控制器代碼:

public function view($id)
{
    $customer = DB::table('customers')->where('id', $id)->first();

    return view('pages.customer.customerView', compact('customer'));
}

請注意,您是如何在public function view()使用DB::table("customers") public function view() 您的關系是在模型Customer上定義的,而不是在DB Facade上定義的,因此您的代碼應為:

public function view($id)
{
    $customer = \App\Customer::where('id', $id)->first();

    return view('pages.customer.customerView', compact('customer'));
}

暫無
暫無

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

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