【问题标题】:Laravel 5.1 hasManyThrough Pivot tableLaravel 5.1 hasManyThrough Pivot 表
【发布时间】:2015-12-14 14:25:17
【问题描述】:

我有模型多对多关系之类的。我想通过数据透视表 CategoryNews 关联 StateCategory

类别模型

class Category extends Model
{
    public function news() {

        return $this->belongsToMany('App\News');

    } 
}

新闻模型

class News extends Model
    {
         public function categories()
        {
            return $this->belongsToMany('App\Category');
        }
        public function state()
        {
            return $this->belongsTo('App\State');
        }
}

和状态模型

class State extends Model
{
    public function news() {

        return $this->hasMany('App\News');

    }  
}

我想选择与 cat_type=2 的状态相关的新闻(来自类别表) 我试过了

$slide_news = State::whereHas('news.categories',function($query){ $query->where('categories.cat_type',2);})

                    ->with(array('news'=>function($query){ 
                    $query->orderBy('created_at', 'desc');}
                   ))->where('id',$id)->first();

但是 cat_type 过滤器不起作用。我也尝试过 hasManyThrough 但我不知道如何使用数据透视表来实现它 请帮忙

【问题讨论】:

    标签: laravel-5 many-to-many pivot-table has-many-through


    【解决方案1】:

    有一个 Laravel 5.5 composer 包可以执行多级关系(深度)

    包装: https://github.com/staudenmeir/eloquent-has-many-deep

    例子:

    User → 属于许多 → Role → 属于许多 → Permission

    class User extends Model
    {
        use \Staudenmeir\EloquentHasManyDeep\HasRelationships;
    
        public function permissions()
        {
            return $this->hasManyDeep(
                'App\Permission',
                ['role_user', 'App\Role', 'permission_role'], // Pivot tables/models starting from the Parent, which is the User
            );
        }
    }
    

    是否需要定义外键的例子:

    https://github.com/staudenmeir/eloquent-has-many-deep/issues/7#issuecomment-431477943


    致版主: 不要删除我的答案

    我花了两天的时间解决了这个问题,我很高兴我找到了我想让全世界知道的解决方案

    请注意,我的回答已被投票,但您已将其删除。

    问题的标题是关于:Laravel 的 hasManyThrough 数据透视表,而我的回答就是这样,在数据透视表上执行 hasManyThrough 等效项的解决方案

    这个问题已经有 3 年的历史了,让我们承认没有人想要特定于该问题的解决方案,因为我们都有自己的解决方案。 如果我是你,我希望得到一个通用的答案。

    【讨论】:

      猜你喜欢
      • 2016-08-04
      • 2016-03-16
      • 1970-01-01
      • 2014-09-19
      • 2021-06-07
      • 2019-02-12
      • 1970-01-01
      • 2021-03-18
      • 1970-01-01
      相关资源
      最近更新 更多