我有三张桌子:
collections
其中有id
,name
genre_collection
其中有id
,genre_id
,collection_id
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
提前致谢。