【发布时间】:2019-07-01 22:32:07
【问题描述】:
我有三张桌子:
-
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
提前致谢。
【问题讨论】:
-
为什么要在收藏表中保存genre_id? ,它已经在genre_collection表中
-
谢谢。我错误地将它添加到问题中。立即删除。
标签: php laravel eloquent eloquent-relationship