Home > Software design >  Laravel - condition on with()
Laravel - condition on with()

Time:10-15

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');
}

CodePudding user response:

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();

CodePudding user response:

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.

  • Related