我有3个表:Laravel多对多获取字段两个表
- 类型型号:ID,姓名,蛞蝓等
- GenreStation型号:ID,genre_id,station_id。
- 站模式:ID,姓名,蛞蝓,标识等
我试图获得通过流派蛞蝓从电台表失调和极限参数数据。但我也想用这个语句来抓取流派名称:
Genre::slug($genreSlug)
->first()
->stations()
->skip($offset)
->take($limit)
->get([
'genres.name as genre_name',
'stations.id',
'stations.name',
'stations.slug',
'stations.stream_url',
'stations.logo',
'stations.media_type',
'stations.bit_rate',
'stations.listeners',
'stations.status',
]);
,我发现了以下错误:
"Illuminate\Database\QueryException","message":"SQLSTATE[42S22]: Column not found: 1054 Unknown column 'genres.name' in 'field list' (SQL: select
genres
.name
asgenre_name
,stations
.id
,stations
.name
,stations
.slug
,stations
.stream_url
,stations
.logo
,stations
.media_type
,stations
.bit_rate
,stations
.listeners
,stations
.status
,genre_station
.genre_id
aspivot_genre_id
,genre_station
.station_id
aspivot_station_id
,genre_station
.created_at
aspivot_created_at
,genre_station
.updated_at
aspivot_updated_at
fromstations
inner joingenre_station
onstations
.id
=genre_station
.station_id
wheregenre_station
.genre_id
= 1 limit 15 offset 0)","file":"/home/vagrant/Projects/MuzzaLife/vendor/laravel/framework/src/Illuminate/Database/Connection.php","line":625
没有genre.name
场一切正常。我怎么解决这个问题?
这是为我工作,但我试图用1查询来解决这个问题,以逃避合并流派和工作站对象。 – Viktor
我认为你的解决方案已经在水中使用了2个查询,但为了得到想要的结果,你还可以添加一个像' - > join('genres','genre_station.genre_id','=','genres.id')的连接。 ',这应该在' - > stations()' –
后面''>站点()'后使用连接解决了问题。我不确定这个变体的优秀性,但它工作正常。谢谢你的帮助! – Viktor