簡體   English   中英

雄辯的ORM有很多槽

[英]Eloquent ORM hasManyTrough

我在數據庫中具有hasManyTrough()關系,但無法使其雄辯地工作。

我數據庫中的關系

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

我有3個型號

Category
  has_many CategoryEntries

Entry
  has_many CategoryEntries

CategoryEntry
  belongs_to Category
  belongs_to Entry

因此,每個類別都有很多條目,每個條目都有很多類別。

在鐵軌我會做以下

Entry
  has_many CategoryEntries
  has_many Categories, through: :category_entries

我雄辯地創造了以下內容

  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');
    }

但這將創建以下sql命令:

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

這毫無意義。 我的錯誤在哪里?

如您的問題所述,關系是

Category (hasMany) Entry (hasMany) CategoryEntries

因此我們可以在Category模型中添加hasManyThrough關系,而不是在Entry模型中添加

class Category
.......

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

UPDATE

如果該關系基於您給定的db,則CategoryEntry之間具有多對多關系。 那么你可以擁有

class Entry
....

public function categories()
{
    return $this->belongsToMany(App\Category::class, 'category_entries');
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM