Laravel |使用 Eloquent hasManyThrough
Laravel | Using Eloquent hasManyThrough
我有一个叫 invoiceDetails
的 table 有 item_id
和另一个叫 items
的 table 一样 foreign key
有 category_id
作为 table 的 foreign key
称为 categories
。
我想使用 eloquent 执行此操作:
$result = InvoiceDetail::groupBy('item_id')
->selectRaw('sum(qty) as qty, item_id')->with('item', 'category')->get();
但我收到错误消息:
Call to undefined relationship [category] on model [App\InvoiceDetail].
这是我在 Category
模型中的关系:
public function invoiceDetail() {
return $this->hasManyThrough('App\InvoiceDetail', 'App\Item', 'category_id', 'item_id');
}
有什么建议吗?
不确定您是否需要此处的 hasManyThrough
关系,除非您想要获取属于所有项目的所有 InvoiceDatail
对象,而这些项目又属于该类别。你的问题那部分不清楚。
但在您的示例中,您正在从不同的 item_id.
中获取其类别的项目
这不起作用的原因是因为您试图从 InvoiceDetail
对象中获取类别关系,该对象不存在。
->with('item', 'category')
您想根据项目关系加载 Category
,而不是基于 InvoiceDetail
,请尝试点符号(假设您确实定义了其他关系)
->with('item.category')
关系应该是这样的:
class InvoiceDetail extends Model
{
public function item()
{
return $this->belongsTo(\App\Item::class);
}
}
class Item extends Model
{
public function invoiceDetails()
{
return $this->hasMany(\App\InvoiceDetail::class);
}
public function category()
{
return $this->belongsTo(\App\Category::class);
}
}
class Category extends Model
{
public function items()
{
return $this->hasMany(\App\Item::class);
}
public function invoiceDetails()
{
return $this->hasManyThrough(\App\InvoiceDetail::class, \App\Item::class, 'category_id', 'item_id');
}
}
如果您有一个类别并且想直接加载所有 InvoiceDetails,您会想要使用 hasManyThrough
。
dd($category->invoiceDetails);
我有一个叫 invoiceDetails
的 table 有 item_id
和另一个叫 items
的 table 一样 foreign key
有 category_id
作为 table 的 foreign key
称为 categories
。
我想使用 eloquent 执行此操作:
$result = InvoiceDetail::groupBy('item_id')
->selectRaw('sum(qty) as qty, item_id')->with('item', 'category')->get();
但我收到错误消息:
Call to undefined relationship [category] on model [App\InvoiceDetail].
这是我在 Category
模型中的关系:
public function invoiceDetail() {
return $this->hasManyThrough('App\InvoiceDetail', 'App\Item', 'category_id', 'item_id');
}
有什么建议吗?
不确定您是否需要此处的 hasManyThrough
关系,除非您想要获取属于所有项目的所有 InvoiceDatail
对象,而这些项目又属于该类别。你的问题那部分不清楚。
但在您的示例中,您正在从不同的 item_id.
中获取其类别的项目这不起作用的原因是因为您试图从 InvoiceDetail
对象中获取类别关系,该对象不存在。
->with('item', 'category')
您想根据项目关系加载 Category
,而不是基于 InvoiceDetail
,请尝试点符号(假设您确实定义了其他关系)
->with('item.category')
关系应该是这样的:
class InvoiceDetail extends Model
{
public function item()
{
return $this->belongsTo(\App\Item::class);
}
}
class Item extends Model
{
public function invoiceDetails()
{
return $this->hasMany(\App\InvoiceDetail::class);
}
public function category()
{
return $this->belongsTo(\App\Category::class);
}
}
class Category extends Model
{
public function items()
{
return $this->hasMany(\App\Item::class);
}
public function invoiceDetails()
{
return $this->hasManyThrough(\App\InvoiceDetail::class, \App\Item::class, 'category_id', 'item_id');
}
}
如果您有一个类别并且想直接加载所有 InvoiceDetails,您会想要使用 hasManyThrough
。
dd($category->invoiceDetails);