I have the following test method in my model, it gets the length of a json column in a row:
public function test(){
return $this->select(DB::raw('JSON_LENGTH((SELECT comments FROM lab_evals WHERE id='.$this->id.'))'))->get();
}
In tinker it returns this:
= IlluminateDatabaseEloquentCollection {#7430
all: [
AppModelsLabEval {#7429
JSON_LENGTH((SELECT comments FROM lab_evals WHERE id =50)): 2,
},
AppModelsLabEval {#7431
JSON_LENGTH((SELECT comments FROM lab_evals WHERE id =50)): 2,
},
],
}
Not really a big deal since I can just call first(), but I’m wondering why there are two objects in the collection instead of one.
I would expect this:
= IlluminateDatabaseEloquentCollection {#7430
all: [
AppModelsLabEval {#7429
JSON_LENGTH((SELECT comments FROM lab_evals WHERE id =50)): 2,
},
],
}
Edit: Here’s the raw SQL that Laravel generates for this query for some model.
"select JSON_LENGTH((SELECT comments FROM lab_evals WHERE id=50)) from `lab_evals`"
The result I’m getting would make sense.
This is the proper raw SQL, but still not sure how I could translate this to a Laravel DB query builder.
(SELECT JSON_LENGTH((SELECT comments from lab_evals WHERE id=50)));
Edit 2:
I ended up just doing this, marking as solved:
DB::select('SELECT JSON_LENGTH((SELECT comments from lab_evals WHERE id='.$this->id.'))')
2
Answers
View my second edit for what I did.
Move your where out of the select, right now it’s not applied to the whole query, only your specific select. Something like this should do the trick.