英文:
How to Avoid Duplicate Data RestfulApi Laravel
问题
我正在使用Laravel创建RESTful API,当我查看课程列表时,重复的内容显示出来了。如何避免重复的数据。为了解决这个问题,我使用了DISTINCT,但它没有起作用。
以下是我附加的API数据,在查看Flutter时显示了两次。Java Basic 我附上了下面的截图图片。
我在Laravel中尝试了以下代码。
$courses = Course::select('courses.id', 'courses.name', 'contents.name as contentsname')
->join('contents', 'contents.course_id', '=', 'courses.id')->distinct()
->get();
return response()->json($courses);
为什么distinct()没有起作用?
英文:
i am creating restful api using laravel while I was viewing the courses list duplicated content was displaying. How to avoid the duplicated data.in order to solved the problem i used DISTINCT but it wasn't works.
[{"id":1,"name":"Java Basic","contentsname":"Java Introduction"},{"id":1,"name":"Java Basic","contentsname":"Java Variable"},{"id":2,"name":"JDBC","contentsname":"Connecting JDBC"}]
i attched the api above while view the flutter it was displayed two times.Java Basic i attached screenshot image below.
what i tried in laravel i attched below of the code.
$courses = Course::select('courses.id', 'courses.name', 'contents.name as contentsname')
->join('contents', 'contents.course_id', '=', 'courses.id')->distinct()
->get();
return response()->json($courses);
why distinct() in not working
答案1
得分: 1
你可以使用groupBy
按列获取唯一的行。在你的Eloquent查询中,你可以这样做:
$courses = Course::select('courses.id', 'courses.name', 'contents.name as contentsname')
->join('contents', 'contents.course_id', '=', 'courses.id')
->groupBy("courses.name")
->get();
groupBy
实际上获取了不同的值,事实上,groupBy
将相同的值分类,以便我们可以对它们使用聚合函数。但在这种情况下,我们没有使用聚合函数,我们只是选择了值,这将导致结果具有不同的值。
英文:
You can anyway use groupBy
to get the unique rows by column, In your eloquent query you can do like this,
$courses = Course::select('courses.id', 'courses.name', 'contents.name as contentsname')
->join('contents', 'contents.course_id', '=', 'courses.id')
->groupBy("courses.name")
->get();
groupBy
is actually fetching the distinct values, in fact the groupBy
will categorize the same values, so that we can use aggregate functions on them. but in this scenario we have no aggregate functions, we are just selecting the value which will cause the result to have distinct values
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论