draw134
draw134

Reputation: 1187

Laravel: How can I check and get the data if the record is existing in either of the two tables?

I have a main table users_mws_reimbursements and it has a column case_id. What I want is to get the record/column from users_mws_reimbursements if the case_id from users_mws_reimbursements is existing in either of the two tables (users_mws_case_logs and admin_case_info). Is that possible?

What I tried is joining the two tables but I think it is not correct since it will check both tables.

 $UsersMwsReimbursements = UsersMwsReimbursements::where('users_mws_reimbursements.users_mws_id', $client->id)
     ->join('admin_case_info','admin_case_info.case_id','users_mws_reimbursements.case_id')
     ->join('users_mws_case_logs','users_mws_case_logs.case_id','users_mws_reimbursements.case_id')
     ->whereDate('users_mws_reimbursements.approval_date', '>', Carbon::now()->subDays(30))
     ->get();

dd($UsersMwsReimbursements);

NOTE: UsersMwsReimbursements model is users_mws_reimbursements

Upvotes: 0

Views: 680

Answers (1)

Peppermintology
Peppermintology

Reputation: 10210

The Laravel Query Builder has whereExists and orWhereExists methods which might be what you are looking for.

Something like the following:

UsersMwsReimbursements::whereDate('users_mws_reimbursements.approval_date', '>', Carbon::now()->subDays(30))
    ->whereExists(function ($query) {
        $query->select(DB::raw(1))
            ->from('users_mws_case_logs')
            ->whereColumn('users_mws_case_logs.case_id', 'users_mws_reimbursements.case_id');
    })->orWhereExists(function ($query) {
        $query->select(DB::raw(1))
            ->from('admin_case_info')
            ->whereColumn('admin_case_info.case_id', 'users_mws_reimbursements.case_id');
    });

Upvotes: 1

Related Questions