2016-03-22 56 views
1

我嘗試在Laravel中定義自定義模型方法。在SubscriptionNotification之間,我有SubscriptionNotification之間的n:m關係。自定義模型方法在Laravel中獲得關係

我已經定義了默認的關係:

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

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

現在我想定義一個方法,它返回的通知的集合。我收集我想在數組中通知的ID和寫下面的方法:

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

但是,當我想$subscription->notifications_due使用的評判,我收到以下錯誤:

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

我對Laravel來說是新的(我來自Rails)。我不知道這是否可能在Laravel中。也許有人可以幫助我。謝謝!

回答

1

刪除方法notifications_due中的->get()部分。 get()將返回一個Collection,但在將該方法作爲屬性(或魔術方法)調用時,Laravel希望該方法返回Relation的實例。然後Laravel將執行查詢並自動將其轉換爲Collection。

此外,您可以使用您已經定義notifications()方法:

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; 

要得到所有的id s收集你可以試試這個:

$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