0

I have a model in my laravel application called Job that uses the display_name attribute. Because of this, I need all of the columns that make up the display name to be included in any query ran on the Job model.

It's unrealistic in my application to remember to include these columns in every query so I have included this piece of code in the boot function of my model to do just that:

static::addGlobalScope('display_name_fields', function (Builder $builder) {
    $builder->addSelect(...)
            ->with([... , ...]);
});

The issue I'm running into now is when the Job model is called without a select in the query (to get all jobs), only the columns in the addSelect are grabbed from the database. For example, these statements will only get the columns in the addSelect: Job::get(); Job::where(...)->get();

The only time the addSelect works as intended is if other columns are specified like this: Job::select('column1')->where(...);

Similarly, if a select() is included in the boot function the display name works but every column is selected: $builder->select()->addSelect...

How can I make sure these columns are included in every query on the Job model without always including every column?

0

1 Answer 1

1

Found the solution!

I can check the columns being selected in my query and if there is no columns or if jobs.* is being selected, then the addSelect will not be added to my query.

static::addGlobalScope('display_name_fields', function (Builder $builder) {
  if(isset($builder->getQuery()->columns) && !in_array('jobs.*', $builder->getQuery()->columns))
     $builder->addSelect(...);
  $builder->with([... , ...]);
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.