2017-05-21 6 views
1

私はユーザのプロファイルを表すテーブルを持っています。このプロファイルは他のプロファイルに従うことができます。ここでループバック: "hasMany"タイプの関係テーブルにデータを追加

は私profil.jsonの一部である

"relations": { 
"followers": { 
    "type": "hasMany", 
    "model": "Profil", 
    "foreignKey": "publisherId", 
    "keyThrough": "subscriberId", 
    "through": "Subscribing" 
}, 
"subscribings": { 
    "type": "hasMany", 
    "model": "Profil", 
    "foreignKey": "subscriberId", 
    "keyThrough": "publisherId", 
    "through": "Subscribing" 
}, 

まあこれは正常に動作しますが、今はプロフィールが登録された日付を知られたく。

だから私は取得する可能性を持ちながら、今、私はこのprofilsのデータを照会できるようにしたいと思い

{ 
"name": "Subscribing", 
    "base": "PersistedModel", 
    "idInjection": true, 
"options": { 
    "validateUpsert": true 
}, 
"properties": { 
    "subscriptionDate": { 
    "type": "date", 
    "required": true, 
    "default": "$now" 
    } 
}, 
"validations": [], 
"relations": { 
    "subscriber": { 
    "type": "belongsTo", 
    "model": "Profil", 
    "as": "subscriber" 
    }, 
    "publisher": { 
    "type": "belongsTo", 
    "model": "Profil", 
    "as": "publisher" 
    } 
}, 
"acls": [], 
"methods": {} 

}

日付を追加するためにsubscribing.json関連テーブルを更新同じ時間内にサブスクリプションの日付。理想的には、関係表を非公開にしておきます。 ありがとう

答えて

0

は、手動でサブスクライバを追加してみます。

まず、次subscribing.json

"scope": { 
    "include": [ 
     "subscriber" 
    ] 
    } 

の横を追加し、profil.jsにフックオブザーバを作成します(私はマッピングにlodashを使用しますが、あなたはあなたのライブラリーを好む使用することができます)

Profil.observe('loaded', function(ctx, next){ 
    const Subscribing = Profil.app.models.Subscribing; 

    Subscribing.find({ 
    where: { 
     publisherId: ctx.data.id 
    } 
    }, function (err, subscribings) { 
    if(err) return next(err) 

    ctx.data.subscribings = _.map(subscribings, function(subscribing){ 
     return { 
     date: subscribing.subscriptionDate, 
     subscriber: subscribing.subscriber 
     } 
    }); 

    next(); 
    }); 
}) 

そして、それはすべてです!問題がある場合は、これを試してコメントしてください。

+0

ありがとう、私はそれを試し、あなたにいくつかのフィードバックをします。ちょうど私にそれを消化する時間を与えてください:) – chd

0

「インクルード」フィルタを使用してリレーションデータをレスポンスに追加できます。 だからあなたの場合には、これは、ユーザーの「subscribings」を取得する必要があります。

Profil.find({include: 'subscribings'}, function() { /* ... */ }); 
+0

を含めることができ

"subscribingMetaData": { "type": "hasMany", "model": "Subscribing", "foreignKey": "subscriberId" } 

次の行を追加、あなたのprofile.jsonでSubscribingMetaData

それを呼び出すとしましょうプロフィールと購読されたプロフィールはありますが、関係表の日付は表示されません。 – chd

+0

さて、あなたが今何を意味しているのか分かりますが、おそらくあなたは次のmixinを見てみるべきでしょう。それはモデルプロパティを通して同じ問題を扱っているようです:https://github.com/JonnyBGod/loopback-set-through-properties-mixin – yotamsha

+0

ありがとう、面白いようです。私は今夜​​これを試して、あなたにフィードバックをします。 – chd

0

彼の答えには、@rigobcastroの片方向が言及されています。

また、新しいリレーションを作成する必要があります。

のは、我々は今、あなたは私が得る、これにより、クエリで

Profil.find({include: ['subscribings', 'subscribingMetaData']}, function() { /* ... */ }); 

// process subscribingMetaData and map subscriptionDate with subscribings to get desired output. 
関連する問題