首页 > 解决方案 > Laravel 中表之间的雄辩关系

问题描述

我有三张桌子:

  1. collections其中有id,name
  2. genre_collection其中有id, genre_id,collection_id
  3. genres其中有id,name

我想从具有基因的集合中检索数据。

集合模型

class Collections extends Model{
    public function genres(){
        return $this->hasMany('App\Models\GenreCollectionRelationships', 'genre_id' , 'id');
    }
}

generic_collection

class GenreCollectionRelationships extends Model{
    public function genre(){
        return $this->hasOne('App\Models\Genres', 'id', 'genre_id');
    }
}

搜索控制器

class SearchController extends Controller{
    $collection->genres;
    foreach($collection->genres as $item){
        $item->genre;
    }
}

这段代码工作正常。输出是

实际的

"genres": [{
    "id": 1,
    "genre_id": 1,
    "collection_id": 1,
    "created_at": "2019-02-07 17:13:36",
    "updated_at": "2019-02-07 17:13:36",
    "genre": {
        "name": "Action",
        "meta": null
    }
}]

有什么办法可以直接得到如下所示的输出

预期的

"genres": [ {
    "name": "Action",
    "meta": null
}]

我尝试了 hasManyThrough,belongsToMany,但没有任何结果。

笔记。我在 laravel 5.7

提前致谢。

标签: phplaraveleloquenteloquent-relationship

解决方案


我假设您想直接从 collection 访问 Generic 。如果是这种情况,您可以在集合模型中直接定义多对多关系到通用模型以访问它。请参考:https ://laravel.com/docs/5.7/eloquent-relationships#many-to-many 。对不起,如果我错了


推荐阅读