quick icon indicating copy to clipboard operation
quick copied to clipboard

Add a shortcut to `whereHas` to compare relationship columns

Open elpete opened this issue 4 years ago • 0 comments

The most common use case of whereHas is to check a value against a column on a relationship. It's rather verbose to do that right now:

var books = getInstance( "Book" )
    .whereHas( "author.publisher", ( qb ) => {
        qb.where( "name", "Penguin" );
    } )
    .get();

Potential options could include:

  1. Overloading whereHas.

If a non-function value is passed as the second argument, we will treat the first argument as a subselect string, common to how addSubselect works.

var books = getInstance( "Book" )
    .whereHas( "author.publisher.name", "Penguin" )
    .get();
  1. Add a new method, such as whereHasValue

Similar to orderByRelated, we could introduce a new method for doing the where check. It would look like the where method on qb but the first argument would be the relationship string.

var books = getInstance( "Book" )
    .whereHasValue( "author.publisher", "name", "Penguin" )
    .get();

This has the added benefit of doing anything where currently does, such as different operators or value subselects.

var books = getInstance( "Book" )
    .whereHasValue( "author.publisher", "name", "<>", "Penguin" )
    .get();
  1. Do both and have whereHas with a non-function second argument pass to whereHasValue.

elpete avatar Feb 18 '21 04:02 elpete