2016-03-22 6 views
1

私はLaravelでカスタムModelメソッドを定義しようとしています。私はSubscriptionNotificationとの間にn:m関係を持っています。SubscriptionNotificationを超えています。Laravelでリレーションを取得するカスタムモデルメソッド

私はすでにデフォルトの関係を定義した:

public function subscription_notifications() { 
    return $this->hasMany('App\SubscriptionNotification'); 
} 

public function notifications() { 
    return $this->belongsToMany('App\Notification', 'subscription_notifications'); 
} 

は、今私は、通知のコレクションを返すメソッドを定義します。私は

[LogicException] 
Relationship method must return an object of type Illuminate\Database\Eloquent\Relations\Relation 

:私は、配列に私が欲しいの通知のIDを収集し、以下の方法で書きます。

public function notifications_due() { 
    // Collect $notification_ids 
    return $this->belongsToMany('App\Notification', 'subscription_notifications')->whereIn('notifications.id', $notification_ids)->get(); 
} 

をしかし、私は$subscription->notifications_dueによって優先mothodを使用したいとき、私は次のエラーを取得します私はLaravelに新しい(私はRailsから来た)。これがLaravelでも可能かどうかはわかりません。たぶん誰かが私を助けることができます。ありがとう!

答えて

1

notifications_due->get()部分を削除します。 get()はコレクションを返しますが、メソッドをプロパティ(またはマジックメソッド)として呼び出すと、メソッドはRelationのインスタンスを返すと想定します。 Laravelはクエリを実行し、それを自動的にコレクションに変換します。

public function notifications_due() { 
    // Collect $notification_ids 
    return $this->notifications()->whereIn('id', $notification_ids); 
} 
+0

感謝を!それはそれだった。 – mgluesenkamp

2

は、例えば、あなたの関係のメソッドからgetの呼び出しを削除します:

public function notifications_due() { 
    return $this->belongsToMany(
     'App\Notification', 
     'subscription_notifications 
    ')->whereIn('notifications.id', $notification_ids); 
} 

はちょうど同じそれを使用します。

// It'll return a collection 
$dues = $subscription->notifications_due; 

また、あなたはあなたが既にnotifications()メソッドを定義し使用することができます

idをすべてあなたはそれが好きで使用している場合かどう

$ids = $dues->pluck('id'); 

また

は、あなたがより多くの制約を追加する可能性があります。:

$dues = $subscription->notifications_due()->where('some', 'thing')->get(); 

するか、ページ付け:コレクションあなたはこれを試すことが

$dues = $subscription->notifications_due()->where('some', 'thing')->paginate(10); 
+1

ありがとうございます。私は両方の答えを受け入れることはできませんが、私はあなたのことを賞賛しました。 – mgluesenkamp

+0

通知の関係をどこに置くことができますか?どこかにModelクラスがありますか?たとえば、複数のユーザーが言及されている場合は、通知とメッセージの間で多対多を行う必要があります。 :) – Blagoh