【问题标题】:Laravel hasManyThrough relationship gives empty collectionLaravel hasManyThrough 关系给出空集合
【发布时间】:2016-01-22 02:14:02
【问题描述】:

我正在尝试获取属于 custom_view 的所有过滤器。例如:$user->custom_views->first->filters

下面的代码给了我一个空集合。我已经尝试了一切,但无法理解为什么我会得到一个空集合。也许有人可以在这里看到我做错了什么?

user      custom_views   custom_view_filters   filters
----      ------------   -------------------   -------
id        id             id                    id
          user_id        custom_view_id
                         filter_id

用户模型:

public function custom_views(){
    return $this->hasMany('App\CustomView');
}

CustomView 模型:

public function user(){
    return $this->belongsTo('App\User');
}

public function filters(){
    return $this->hasManyThrough('App\Filter', 'App\CustomViewFilter', 'custom_view_id', 'id');
}

CustomViewFilter 模型:

no relations defined

过滤器模型

public function custom_views(){
    return $this->belongsToMany('App\CustomView', 'custom_view_filter', 'custom_view_id', 'filter_id');
}

【问题讨论】:

  • custom_view 和 filter 之间似乎有直接关系,使用数据透视表的简单多对多关系。我错了吗?
  • 是的,你是对的。 return $this->belongsToMany('App\Models\Filter')->withPivot('custom_view_id', 'filter_id', 'position'); 确实有效。我发现了问题,我的表被命名为 custom_view_filters 而 laravel 试图找到 custom_view_filter 。谢谢

标签: mysql laravel laravel-5 eloquent relationship


【解决方案1】:

将CustomView 中的filters 方法更改为:

public function filters(){
    return $this->belongsToMany('App\Filter', 'custom_view_filter','filter_id','custom_view_id');
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-10-18
    • 2023-03-09
    • 2018-07-24
    • 2020-10-14
    • 1970-01-01
    • 1970-01-01
    • 2018-03-08
    • 2021-12-06
    相关资源
    最近更新 更多