英文:
Laravel relationships eager loading: Call to undefined function productListing()
问题
我有一系列相关的模型,我想一次性使用Eloquent的急加载功能加载它们,参考https://laravel.com/docs/10.x/eloquent-relationships#nested-eager-loading。在我的情况下,我正在尝试执行以下操作:
$order = Orders::where('id', $orderId)
->with([
"users",
"shippingInvoices" => [
"shippingInvoiceDetails" => [
"orderDetails" => "productListing",
],
"vendor"
]
])->get();
但我遇到了以下错误:调用未定义的函数productListing()。
在Orders模型定义文件Orders.php中,我有:
public function users() {
return $this->belongsTo('App\Users', 'user_id');
}
public function shippingInvoices() {
return $this->hasMany(ShippingInvoice::class, "order_id");
}
在ShippingInvoice.php中,我有:
public function shippingInvoiceDetails(): HasMany
{
return $this->hasMany(ShippingInvoiceDetails::class, "invoice_id");
}
在ShippingInvoiceDetails.php中:
public function orderDetails(): BelongsTo
{
return $this->belongsTo(OrderDetails::class);
}
在OrderDetials.php中:
public function productListing() {
return $this->belongsTo('App\ProductListing', 'product_id');
}
英文:
I have a chain of related models that I want to load up together at once using Eloquent's eager loading feature, as per https://laravel.com/docs/10.x/eloquent-relationships#nested-eager-loading. In my own case, I am trying to do:
$order = Orders::where('id', $orderId)
->with([
"users",
"shippingInvoices" => [
"shippingInvoiceDetails" => [
"orderDetails" => "productListing",
],
"vendor"]
])->get();
But I get the following error: Call to undefined function productListing().<br>
In the Orders model definition file, Orders.php, I have:
public function users() {
return $this->belongsTo('App\Users', 'user_id');
}
public function shippingInvoices() {
return $this->hasMany(ShippingInvoice::class, "order_id");
}
In ShippingInvoice.php, I have:
public function shippingInvoiceDetails(): HasMany
{
return $this->hasMany(ShippingInvoiceDetails::class, "invoice_id");
}
In ShippingInvoiceDetails.php:
public function orderDetails(): BelongsTo
{
return $this->belongsTo(OrderDetails::class);
}
In OrderDetials.php:
public function productListing() {
return $this->belongsTo('App\ProductListing', 'product_id');
}
答案1
得分: 1
你需要按照以下方式调用它:
$order = Orders::where('id', $orderId)
->with([
"users",
"shippingInvoices",
"shippingInvoices.shippingInvoiceDetails",
"shippingInvoices.shippingInvoiceDetails.orderDetails",
"shippingInvoices.shippingInvoiceDetails.orderDetails.productListing",
"vendor"
])->get();
你可以使用点号(.)来访问相关的模型。
英文:
You have to call it like bellow.
$order = Orders::where('id', $orderId)
->with([
"users",
"shippingInvoices",
"shippingInvoices.shippingInvoiceDetails",
"shippingInvoices.shippingInvoiceDetails.orderDetails",
"shippingInvoices.shippingInvoiceDetails.orderDetails.productListing",
"vendor"
])->get();
you can access the related model with dot (.)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论