Not in. There should be example in query Builder chapter. Unless I misunderstood the question.
Opposite of `select` in query builder?
Is there any method in query builder that behave opposite of select method ? I want to get every columns Except the given columns?
$user->comments()->someMthodToGetEveryThingExceptTheseFields(['filed', 'field2'])->get();
The method you mentioned is whereNotIn which is not behave like above
Laravel has a when method, not positive of your use case but have a look.
If I understand you correctly?
You have a table with 5 fields something like this
- id
- title
- artist
- released
- barcode
and you don't want to load two of them, meaning in your query you only want to get
- title
- artist
- released
If so the easiest way is to
Model::get('title', 'artist', 'released');
@tray2 In you example, I want to ignore artist field, but i want some method to get everything exceptartist:
Model::dontSelect(['artist'])->get();
instead of :
Model::select(['id','title','released','barcode'])->get();
sorry for my poor english @jlrdw, The word was 'Except'
No, but one column not loaded is that really helping much?
If you want to export the data via an api and have certain columns not present in the output then you can use the hidden() method
In my model i have 20 fields, i want to select 14 of them, So excluding 6 of them is better than selecting 14 fields
To your model, add a property that represents the columns you want in this use case
public static $subSet=['field1','field6'.'field7','field8','field9','field11','field12'];
then in the query
select(MyModel::subSet)->...
If its not worth doing this because you only write this query once, then you have wasted SO much time on this thread.
Nice one @snapey this one is going into my nice to have snippet collection.
probably better written into a scope
Just select the fields you want to, leave out fields you don't want.
You can use the ide-helper:model command to generate class annotations including the actual columns, then use reflection class to get them in runtime.
protected static $columns;
public function scopeSelectWithout($query, $withoutColumns)
{
if (!static::$columns) {
$rc = new \ReflectionClass(static::class);
static::$columns = collect(explode("\n", $rc->getDocComment()))
->filter(fn($columnLine) => Str::startsWith($columnLine, ' * @property '))
->map(function ($columnLine) {
$columnLine = explode(' ', $columnLine);
return str_replace('$', '', array_pop($columnLine));
});
}
$query->select(array_diff(static::$columns, $withoutColumns));
return $query;
}
Please or to participate in this conversation.