简体   繁体   中英

How to implement nested MySQL query in Laravel Eloquent using Laravel 5.6

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM