现在在 laravel 中,我有一个非常简单的函数,它通过 ajax 调用返回查询结果$sql = " SELECT itemID, itemTime, t2.itemCommentType, t2.itemCOmment FROM ITEM T1 INNER JOIN COMMENTS T2 ON T1.itemID = t2.itemID";try { return DB::connection('mysql')->select($sql);} catch (Exception $e) { return false;}这工作正常,但由于注释类型,它返回两行,其中 id 和 time 对于两者都是相同的itemID | itemTime | itemCommentType | itemComment--------------------------------------------------------------123 09-11-2019 Title Testing123 09-11-2019 Comment New Comment我应该如何更改我的代码(不是查询)以仅返回一个具有一个 ID 和时间的对象,但创建一个包含每种评论类型的数组?我只想要一个结果,但我需要能够在网页的不同区域显示标题和评论
2 回答
![?](http://img1.sycdn.imooc.com/54584c9c0001489602200220-100-100.jpg)
慕的地8271018
TA贡献1796条经验 获得超4个赞
使用模型。在项目模型中-
public function itemComents(){
return $this->hasMany('ItemComment::class', 'itemId');
}
得到你的结果-
Item::with('itemComments')->find(123);
获取所有带有评论的项目
Item::with('itemComments')
![?](http://img1.sycdn.imooc.com/5458692c00014e9b02200220-100-100.jpg)
幕布斯7119047
TA贡献1794条经验 获得超8个赞
我认为你应该像这样按 ItemId 和 itemTime 列分组:
DB::connection('mysql')->select($sql)->where('itemID',$id)->groupBy('itemID','itemTime')->first()
- 2 回答
- 0 关注
- 164 浏览
添加回答
举报
0/150
提交
取消