1

我有 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_itemsnull时它会在顶部存在时返回dd($invoice->toArray())!另一方面,当我使用$invoice->invoiceItems它时效果很好!现在这种差异的原因是什么?

4

1 回答 1

1

改为使用$invoice->invoiceItems

你可以在我认为的关系属性中找到它。

为了数组执行 laravel 逻辑,他们选择将所有内容都包含为 kebab_case 以保持数据一致,但我理解您的困惑。

于 2020-05-10T06:24:11.263 回答