获取与注册关联的发票编号

时间:2018-07-08 11:56:56

标签: laravel

我想获取与注册ID相关的发票编号。所以我有这段代码:

  $user = Auth::user();

  $registration = $user->registrations()->
  with(["invoice"])->where("id", $regID)->first();

但是它不起作用,你知道为什么吗?

dd($registration)显示:

Registration {#342 ▼
  #relations: array:1 [▼
    "invoice" => Invoice {#353 ▼
      #attributes: array:5 [▼
        "id" => 1
        "invoice_number" => 0125
        "registration_id" => 1
        "updated_at" => null
      ]
      #original: array:5 [▶]
    }
  ]
}

dd($registration->invoice);”显示:

"Y"

dd($registration->invoice->invoice_number)显示为“ Trying to get property of non-object”。

注册模型:

public function invoice()
    {
        return $this->hasOne('App\Invoice');
    }

发票模型:

class Invoice extends Model
{
    public function registration()
    {
        return $this->belongsTo('App\Registration');
    }
}

1 个答案:

答案 0 :(得分:0)

您与invoice表中的registrations列和模型中的invoice关系名称不匹配。只需更改发票关系名称

注册模型:

public function invoiceRow()
{
    return $this->hasOne('App\Invoice');
}

这将起作用,当您拥有注册ID时,您可以像这样

$registration = Registration::with('invoiceRow')->where("id", $regID)->first();

dd($registration->invoiceRow->invoice_number)