Skip to content

Instantly share code, notes, and snippets.

@devrkd
Last active July 24, 2019 05:30
Show Gist options
  • Save devrkd/02e51769ae63e486282f549e66e6af1a to your computer and use it in GitHub Desktop.
Save devrkd/02e51769ae63e486282f549e66e6af1a to your computer and use it in GitHub Desktop.
Laravel example code with wherehas
<?php
/*
* example code gist,
*/
Model_A::whereHas('Model_B',
function (\Illuminate\Database\Eloquent\Builder $builder) {
$builder->upcoming()->where('cancel_reason', Model_B::REASON_NOT_AVAILABLE);
})->active();
/*
* The raw query for above statement converts as:
select * from `table_a`
where exists (
select * from `table_b`
where `table_a`.`table_b_id` = `table_b`.`id`
and `cancel_reason` = 'not_available' and `table_b`.`datetime` > now() and `table_b`.`deleted_at` is null)
and `table_a`.`status` = 1
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment