【问题标题】:Laravel | Using Eloquent hasManyThrough拉拉维尔 |使用 Eloquent hasManyThrough
【发布时间】:2018-05-10 16:56:56
【问题描述】:

我有一个名为 invoiceDetails 的表,其中 item_id 来自另一个名为 items 的表中的 foreign key,该表中的 category_idforeign 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');
}

有什么建议吗?

【问题讨论】:

  • doc 中所述,最后尝试添加'id'、'id'。是的,这个方法应该写在 InvoiceDetail 模型中。不在类别模型中

标签: laravel eloquent relationship has-many-through laravel-5.5


【解决方案1】:

不确定您是否需要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);

【讨论】:

  • 很好的答案,点符号有效。您能否解释一下“hasManyThrough”的用法,因为我没有找到任何有用的参考资料?
  • @CairoCoder 该文档实际上包含了一个很好的示例,请参阅laravel.com/docs/5.5/eloquent-relationships#has-many-through
  • 不,没有,它遵循 hasMany's 的路径 :)
猜你喜欢
  • 2014-11-12
  • 1970-01-01
  • 2021-06-22
  • 2017-10-18
  • 1970-01-01
  • 1970-01-01
  • 2020-03-29
  • 2018-09-11
  • 2020-03-11
相关资源
最近更新 更多