dqlb38410 2017-08-01 10:11
浏览 34
已采纳

雄辩的ORM hasManyTrough

i have a hasManyTrough() relation in my database but could not get it to work with eloquent.

the relation in my database

category(id)
entry(id)
category_entries(category_id, entry_id)

i have 3 models

Category
  has_many CategoryEntries

Entry
  has_many CategoryEntries

CategoryEntry
  belongs_to Category
  belongs_to Entry

so every category has many entries and every entry has many categories.

in rails i would do the following

Entry
  has_many CategoryEntries
  has_many Categories, through: :category_entries

i have created the following in eloquent

  CategoryEntry
    public function category(){
        return $this->belongsTo('App\Category');
    }
    public function entry(){
        return $this->belongsTo('App\Entry');
    }

  Category
    public function categoryEntries(){
        return $this->hasMany('App\CategoryEntry');
    }

  Entry
    public function categoryEntries(){
        return $this->hasMany('App\CategoryEntry');
    }


    public function categories()
    {
        return $this->hasManyThrough('App\Category', 'App\CategoryEntry', 'category_id', 'id');
    }

but this will create the following sql command:

select `entries`.*, `category_entries`.`category_id` from `entries` 
inner join `category_entries` on `category_entries`.`id` = `entries`.`entry_id`

this makes no sence. where is my mistake?

  • 写回答

1条回答 默认 最新

  • dongshan1959 2017-08-01 10:16
    关注

    As described in your question, relation is

    Category (hasMany) Entry (hasMany) CategoryEntries

    So we can add hasManyThrough relation in Category Model not in Entry model

    class Category
    .......
    
    public function categoryEntries()
    {
        $this->hasManyThrough(App\CategoryEntry::class, App\Entry::class);
    }
    

    UPDATE

    if the relation is based on db you have given, then you have Many-Many relation between Category and Entry. then you can have,

    class Entry
    ....
    
    public function categories()
    {
        return $this->belongsToMany(App\Category::class, 'category_entries');
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看