Recommand · October 14, 2021 0

Laravel – condition on with()

I wanted to join table NotificationTypes with UserEnabledNotificationTypesId on the NotificationTypesId column of UserEnabledNotifications , only for the rows in which deleted_at column of NotificationTypes table is null. I’ve tried as below. But it is not sorting for the null value of deleted_at column in NotifocationTypes table. Any solutions?

UserEnabledNotifications::with('userNotications', function ($query){
    $query->whereNull('deleted_at');
})->select('userId','notificationTypesId')->get();

UserEnabledNotifications

public function userNotifications(){
  return $this->belongsTo(NotificationTypes::class, 'notificationTypesId','id');
}

You need to pass the with/closure as an array key/value pair

UserEnabledNotifications::with(['userNotifications' => function ($query){
    $query->whereNull('deleted_at');
}])->select('userId','notificationTypesId')->get();

To get only the UserEnabledNotifications that have userNotifications that aren’t deleted, you need whereHas

UserEnabledNotifications::whereHas('userNotifications', function(Builder $query) {
    $query->whereNull('deleted_at');
})
    ->with(['userNotifications' => function($query) {
        $query->whereNull('deleted_at');
    }])->select('userId', 'notificationTypesId')->get();

Try with this query replace column with actual column. No need to check for the NULL value of deleted_at. It will default check for NULL.

UserEnabledNotifications::with(['userNotifications', function ($query){
    $query->orderBy('column', 'ASC');
}])->select('userId','notificationTypesId')->get();

Let me know the results.