我试图将刀片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');
});
有人能够看到我错过的东西吗?
Revelant Controller Code:
public function view($id)
{
$customer = DB::table('customers')->where('id', $id)->first();
return view('pages.customer.customerView', compact('customer'));
}
答案 0 :(得分:0)
注意您在DB::table("customers")
中如何使用public function view()
?您的关系是在模型Customer
上定义的,而不是在DB
外观上定义的,所以您的代码应该是:
public function view($id)
{
$customer = \App\Customer::where('id', $id)->first();
return view('pages.customer.customerView', compact('customer'));
}