0

This is my MySQL query:

SELECT * FROM cc_calenders 
WHERE 
   cc_calenders.user_id = 1 
OR 
   cc_calenders.id = (
           SELECT cc_calender_shares.calender_id 
           FROM cc_calender_shares 
           WHERE 
                cc_calender_shares.shared_with = 'epsita@matrixnmedia.com')

I tried to write the Laravel eloquent code like this:

$records    = Calender::where('user_id', $user_id)
                        ->orWhere('id', function($query) use ($user_email) {
                                $query->table('calender_shares')
                                      ->select('calender_shares.calender_id')
                                      ->where('calender_shares.shared_with', $user_email);
                        })->get();

I am getting this error:

Call to undefined method Illuminate\Database\Query\Builder::table()

What am I doing wrong?

Sayed Mohd Ali
  • 2,156
  • 3
  • 12
  • 28
Saswat
  • 12,320
  • 16
  • 77
  • 156
  • 1
    Possible duplicate of [How to do this in Laravel, subquery where in](https://stackoverflow.com/questions/16815551/how-to-do-this-in-laravel-subquery-where-in) – Rwd Mar 05 '19 at 07:37

2 Answers2

1

You can try

$records    = Calender::where('user_id', $user_id)
                        ->orWhere('id', function($query) use ($user_email) {
                                $query->select('calender_id')
                                      ->from('calender_shares')
                                      ->where('shared_with', $user_email);
                        })->get();

How to do this in Laravel, subquery where in

Xavier Au
  • 21
  • 2
1

Since nobody could answer me before I get my own answer, I am putting the code down here for people who might stumble on same problem.

The main issue was, I was using table() function in the subquery. The better solution was to use from() function.

The code snippet from(with(new CalenderShare)->getTable()) would provide me a the table name of model CalenderShare.

Calender::where('user_id', $user_id)
          ->orWhereIn('id', function($query) use ($user_email) {
                               $query->from(with(new CalenderShare)->getTable())
                                       ->select('calender_shares.calender_id')
                                       ->where('calender_shares.shared_with', $user_email);
                            })->get();
Saswat
  • 12,320
  • 16
  • 77
  • 156