1
store.findRecord('school', school_id, {
                 include: [
                  'students',
                  'students.records'
                 ].join(',')

使用上述代码在初始加载中获取学校、学生、学生的记录数据。在初始加载中,我不需要students.records(最初只列出学生)

仅在单击某个按钮时才需要学生记录(所有学生表现 - 显示表现图表)有没有办法单独获取相关记录并与现有模型链接

我有单独的 api 端点来获取学生的记录

4

1 回答 1

0

强调文本,您可以使用嵌套路由吗?也许是这样的:

// router.js
Router.map(function() {
  // ...
  this.route('school', { path: ':school_id' }, function() {
    this.route('performance');
  });
  // ...
})

// the school route
import Route from '@ember/routing/route';

export default class extends Route {
  async model(params) {
    const { school_id } = params;

    const school = await store.findRecord(
      'school', school_id, { include: 'students' }
    );

    return { school }          
  }
}

// the performance route
import Route from '@ember/routing/route';

export default class extends Route {
  async model() {
     // get the id from the parent route
    const { school_id } this.paramsFor('school');

    const school = await store.findRecord(
      'school', school_id, { include: 'students.records' }
    );
    // depending if the relationship is async or not, students
    // will need to be awaited
    const students = await school.students;

    return { students }          
  }
}

这都使用相同的schools端点。如果您只想获取学生的记录而不访问学校的端点,这取决于您的 API 的功能。

如果您想获取单个学生的记录,您可能希望为该学生创建一个子路由,并执行以下操作:

// router.js
Router.map(function() {
  // ...
  this.route('school', { path: ':school_id' }, function() {
    this.route('performance');
    this.route('students', function() {
      this.route('student', { path: ':student_id' });
    });
  });
  // ...
})

你会像这样链接到那条路线:

{{#link-to 'school.students.student' school_id student_id}}
  Student Name
{{/link-to}}

在你的学生路线中,你想像这样构建你的模型钩子:

// the student route
import Route from '@ember/routing/route';

export default class extends Route {
  async model(params) {
     // get the id from the parent route
    const { school_id } this.paramsFor('school');
    const { student_id } = params;

    const student = await store.findRecord(
      'student', student_id, { include: 'records' }
    );

    // depending if the relationship is async or not, students
    // will need to be awaited
    const records = await student.records;

    return { student, records };     
  }
}

如果您不确定如何与 API 交互,您可能需要针对您的 API 提出另一个问题。在那里我们可以探索它的结构,比如它是http://jsonapi.org/ API 还是非标准的 rest api。

希望这可以帮助。

于 2018-10-09T09:19:56.000 回答