我有 2 个模型:Invoice
并且InvoiceItems
这些模型与invoice_id
:
Schema::create('invoice_items', function (Blueprint $table) {
$table->bigInteger('invoice_id')->unsigned();
$table->foreign("invoice_id")->references('id')->on('invoices')->onDelete('cascade');
});
Invoice
:
class Invoice extends Model
{
protected $fillable = [
'profile_id',
'invoice_number',
....
];
public function invoiceItems()
{
return $this->hasMany('App\InvoiceItem');
}
}
和InvoiceItems
class InvoiceItem extends Model
{
protected $guarded = [];
public function invoice()
{
return $this->belongsTo('App\Invoice');
}
}
当我想使用 eloquent 获取包含发票项目的发票时,我使用以下代码:
$invoice = Invoice::with('invoiceItems')->findOrFail($id);
现在的输出dd($invoice->toArray())
是:
array:20 [▼
"id" => 14
"profile_id" => 13
"invoice_number" => null
....
"created_at" => "2020-05-05 09:21:46"
"updated_at" => "2020-05-09 12:09:14"
"invoice_items" => array:1 [▼
0 => array:10 [▼
"id" => 9
"invoice_id" => 14
"price" => "10000.00"
"created_at" => "2020-05-05 09:21:46"
"updated_at" => "2020-05-05 09:21:46"
]
]
]
到目前为止,一切看起来都很好,但我很困惑!当我想使用$invoice->invoice_items
它null
时它会在顶部存在时返回dd($invoice->toArray())
!另一方面,当我使用$invoice->invoiceItems
它时效果很好!现在这种差异的原因是什么?