【问题标题】:Laravel Categories Map RelationshipLaravel 类别映射关系
【发布时间】:2015-03-15 21:29:12
【问题描述】:

我有以下三个表,但我不知道如何在类别和其他数据类型之间建立关系,在本例中为“页面”:

帖子:

post_id    | title        | slug
1          | Test         | test
2          | Another test | another test

类别地图:

id | category_id | referrer_id | category_map_type
1  | 2           | 1           | Post
2  | 3           | 2           | Post
3  | 2           | 9           | Page

类别

id | name
1  | Laravel
2  | Zend2
3  | Phalcon

所以每当我阅读一个类别时,我都喜欢能够做这样的事情

foreach($category->destinations) ...

到目前为止,我一直尝试使用 hasManyThrough,但没有成功。

【问题讨论】:

    标签: laravel many-to-many relationship has-many-through


    【解决方案1】:

    您拥有的是一个many-to-many relation,对关系进行了一些额外的过滤(对于category_map_type)。试试这个:

    后模型

    public function categories(){
        return $this->belongsToMany('Category', 'category_map', 'referrer_id')
                    ->where('category_map_type', 'Post');
    }
    

    类别模型

    public function posts(){
        return $this->belongsToMany('Post', 'category_map', 'category_id', 'referrer_id')
                    ->where('category_map_type', 'Post');
    }
    

    用法

    $category = Category::find(1);
    foreach($category->posts as $post){
        // ...
    }
    

    Post 也是如此)


    您可能还想查看polymorphic many-to-many relations

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-29
      • 2020-05-20
      • 2016-07-21
      • 2020-12-19
      • 2013-08-03
      相关资源
      最近更新 更多