我的項目表上有多態關系public function categories(): MorphToMany{ return $this->morphToMany(Category::class, 'categorizable', 'categorizables', 'categorizable_id', 'category_id') ->withTimestamps();}有用。我按預期得到了對象列表。只是,我的數據庫中的某些模型始終只有一個類別。我想避免獲得項目列表。我想要直接的對象。我嘗試過,但它不起作用:public function category(){ return $this->morphToMany(Category::class, 'categorizable', 'categorizables', 'categorizable_id', 'category_id')->first;}Call to undefined method App\Models\Category::addEagerConstraints()我有這樣的結果:{ 'id': 1, 'name': 'My name', 'categories': [ {my object category} ]}我想 :{ 'id': 1, 'name': 'My name', 'category': {my object category}}我怎樣才能做到這一點?這是一種多對多的多態關系。
如何獲取第一個具有 morphToMany 關系的對象?
慕的地8271018
2023-07-08 20:22:11