dqlb38410 2017-08-01 02: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 02: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');
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部