繁体   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