如何避免重复数据RestfulApi Laravel

huangapple go评论67阅读模式
英文:

How to Avoid Duplicate Data RestfulApi Laravel

问题

我正在使用Laravel创建RESTful API,当我查看课程列表时,重复的内容显示出来了。如何避免重复的数据。为了解决这个问题,我使用了DISTINCT,但它没有起作用。

以下是我附加的API数据,在查看Flutter时显示了两次。Java Basic 我附上了下面的截图图片。

如何避免重复数据RestfulApi Laravel

我在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.
如何避免重复数据RestfulApi Laravel

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

huangapple
  • 本文由 发表于 2023年6月1日 14:33:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76379236.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定