【问题标题】:What is the best practice when displaying data from more than one table显示来自多个表的数据时的最佳做法是什么
【发布时间】:2016-12-30 09:24:06
【问题描述】:

我有三个表,'sessions'、'classes' 和 'schedules',它们相互连接。

会话:id、名称、描述

类:id、session_id、名称

时间表:class_id、session_id、日期

一个班级属于一个课程,而时间表是一个 N:M 关系,这使您有机会在一个班级中为每个课程设置特定日期。

当我必须显示这些信息时,我的问题就出现了,我有一个显示所有会话的功能:

$sessions = Session::all();

我还有另一个函数可以显示特定课程和特定会话的日期,如下所示:

$result = Schedule:where('class_id','=',$classId)->where('session_id','=',$essionId)->first();

假设我有 30 个课程用于一个课程,当涉及到我用 AngularJS 编写的前端应用程序时,我不知道如何使用 ng-repeat 遍历所有课程然后制作另一个使用 ng-repeat 迭代的调用来调用计划以显示会话的日期,我猜这在 AngularJS 中不是一个好习惯。

谁能告诉我处理这个问题的最佳选择是什么?我必须修改后端吗?比如编辑 Session:all();查询是否还包括 Schedule 表?或者最好的方法是什么?

【问题讨论】:

    标签: javascript angularjs laravel


    【解决方案1】:
    1. 我想你已经在模型中配置了你的关系,如果没有看here

    2. 就我而言,我使用Fractal来自定义显示数据。还有一种方便的方法叫做Available includes 所以你可以像/sessions/?include=classes这样请求你的数据并得到输出

    {data: [{ session_id: 1, some: "data", classes:[{ class_id: 11, some: "class_data" }] }]}

    【讨论】:

      【解决方案2】:

      我会“急切地加载”数据,因此您可以通过加载的对象访问所有对象的父对象。这样,您只需遍历 1 个对象即可一一填充表格行。

      在 Laravel 网站上有 excellent documentation 关于预加载,所以我建议你从那里开始

      【讨论】:

      • 我已经这样做了: public function schedule() { return $this->belongsToMany('App\Schedule', 'schedules', 'session_id', 'id');在 ctrl 我有这个: $sessions = Session::with('schedule')->get();但我收到错误语法错误或访问冲突:1066 Not unique table/alias: 'schedules' (SQL: select schedules.*, schedules.session_id as pivot_session_id, schedules.@987654327 @ as pivot_id from schedules inner join schedules on schedules.id = schedules.id where schedules.session_id in (1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
      猜你喜欢
      • 2016-11-28
      • 2023-02-08
      • 2018-03-19
      • 1970-01-01
      • 2021-01-17
      • 1970-01-01
      • 2011-06-30
      • 2021-05-18
      • 1970-01-01
      相关资源
      最近更新 更多