php - Laravel 中表之间的雄辩关系
问题描述
我有三张桌子:
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
提前致谢。
解决方案
我假设您想直接从 collection 访问 Generic 。如果是这种情况,您可以在集合模型中直接定义多对多关系到通用模型以访问它。请参考:https ://laravel.com/docs/5.7/eloquent-relationships#many-to-many 。对不起,如果我错了
推荐阅读
- python - 我想根据另一个表中的条件过滤表列上的值
- webpack - Webpack 5 - 资产模块 - url-loader 的缺失功能 - postTransformPublicPath
- ms-access - 为什么我的 Accessdb 查询中出现“类型不匹配”错误?
- listview - 带有 StreamBuilder 的 ListBuilder 不返回结果
- rust - 东京::try_join!当其中一项任务返回 Err 时不返回 Err 变体?
- jquery - 为什么jquery POST不能处理数据:数据和处理数据:{data:data}?
- vba - 在 MSProject 中将值设置为 Duration
- html - 父 div 是自动溢出的。子 div 超出父级。如何显示子div?
- azure - 有什么方法可以检查 Azure 服务总线中 IMessageSender 连接的活跃度吗?
- mysql - MySql ROW_NUMBER() 函数在大数据集下的性能如何?