如何在Ember.js中保存多对多关系的模型? [英] How to save models with many-to-many relationship in Ember.js?

查看:110
本文介绍了如何在Ember.js中保存多对多关系的模型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到这个问题已经很久了,我觉得我错过了一些明显的东西。这是我的病例的简化模型:

I'm stuck with this problem for so long that I think that I'm missing something obvious. Here's simplified model of my case:

有 c>患者,具有他/她所有的药物。还有 Medicine ,所有患者都服用它。

There is Patient that has all meds that he/she takes. And there is Medicine that has all patients who takes it.

// Patient model
Yo.Patient = DS.Model.extend({
    firstName: DS.attr('string'),
    lastName: DS.attr('string'),
    meds: DS.hasMany('medicine')
});
// Medicine model
Yo.Medicine = DS.Model.extend({
    title: DS.attr('string'),
    patients: DS.hasMany('patient')
});

我已阅读官方手册和许多资源。最后一个,最接近我的案子是这个。以下是我现在所做的工作:

I've read official manual and many resources. The last one and closest to my case was this Toptal tutorial. Here's what I do now:


  1. 在储存新患者之前,我正在推送医学对象到 newPatient.meds

  2. 然后我保存 newPatient

  3. 保存完成后,我将通过数组医药对象推 newPatient ,并保存每个。

  1. Before saving new patient I'm pushing array of Medicine objects to newPatient.meds.
  2. Then I save newPatient.
  3. After save is done I'm going through array of Medicine objects pushing newPatient to each of them and saving each.

newPatient.get('meds').pushObjects(meds);
newPatient.save().then(function (p) {
    for (var i = 0; i < meds.length; i++) {
        meds[i].get('patients').pushObject(p);
        meds[i].save();
    };
});


但结果不是什么意思be。

But result isn't what it meant to be.


  1. 保存的病人没有任何药物。在 POST 请求服务器 meds 是空数组。

  2. 患者中有患者ID 。但是它在数组的零位置总是有 null

  1. Saved patient doesn't have any meds. In POST request to server meds is empty array.
  2. Saved meds each has patient id in patients. But it always has null on zero position of array.

在StackOverflow上的问题类似。但解决方案不是很有用。而答案是1.5岁,这是Ember世界的永恒。

Also there already was similar question on StackOverflow. But solution is not very usable. And answer is 1.5 years old which is eternity in Ember world.

修改
由Josh发表评论 RecordArray ,因为我现在看不到在我的情况下使用。或者也许可以,但我不知道如何。我有一个创建新病人的表格。有药物清单列表。所以我只需要检查一下 newPatient.meds

Edit Proposed in comments by Josh RecordArray as I see now cant't be used in my case. Or maybe it can, but I don't know how. I have a form for creating new patient. There's list of meds checkboxes. So I need to push only checked ones to newPatient.meds.

我现在做的是:检查复选框(等于相应的对象ID),然后获取每个id的 Medicine 实例,并将其放在数组中。然后我试着把它推入`newPatient.meds'。

What I do now: I get ids of checked checkboxes (which equals to corresponding object id), then get Medicine instance for each id and put it in array. Then I try to push it in `newPatient.meds'.

推荐答案

你应该使用serializer来解决这个问题。
这里是您的问题的答案

You should use serializer for this issue. Here is answer to your question

这篇关于如何在Ember.js中保存多对多关系的模型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆