自定义模型方法以在Laravel中获取关系


Custom model method to get a relation in Laravel

我试图在Laravel中定义一个自定义的Model方法。在CCD_ 3上,CCD_ 1和CCD_。

我已经定义了默认关系:

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)。我不知道这在拉拉威尔是否可能。也许有人能帮我。谢谢!

删除方法notifications_due中的->get()部分。get()将返回一个Collection,但当将该方法作为属性(或魔术方法)调用时,Laravel希望该方法返回Relation的实例。然后Laravel将执行查询并自动将其转换为Collection。

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

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

从关系方法中删除Subscription0调用,例如:

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,您可以尝试以下操作:

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

此外,如果你想使用,你可以添加更多的限制

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

或分页:

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