Danny Bevers
Danny Bevers

Reputation: 853

Laravel mysql json data selecting

I got a database running on mysql 5.7.11 and has a lot of data into a table with JSON column. I got a raw query like this one.

select * from `note` 
where `note_structure_id` = 3 
and JSON_EXTRACT(LCASE(data), '$._letter') = 'a' 
and JSON_EXTRACT(data, '$._number') = 1

Running in sequel pro or phpmyadmin it gives me a result what i expect;

{"_letter": "A", "_number": 1}

The same query i build with laravel it gives me a result of nothing. An empty array. My code to building the same query i got this kind of code.

$result = \DB::table( 'note' )->where( 'note_structure_id', $structureId );

if( is_array( $query ) ) {
    if( isset( $query['where'] ) ) {
        foreach( $query['where'] AS $field => $value ) {
            if( is_numeric( $value ) ) {
                $result = $result->where( \DB::raw( "JSON_EXTRACT(data, '$._{$field}')" ), '=', $value );
            }
            else {
                $result = $result->where( \DB::raw( "JSON_EXTRACT(LCASE(data), '$._{$field}')" ), '=', strtolower( $value ) );
            }
        }
    }
}

dd($result->get());

Did anyone knows what i did wrong with my code or something. I try everything what's possible for fixing it but without result.

Thanks!

Upvotes: 2

Views: 1709

Answers (1)

mrhn
mrhn

Reputation: 18926

Saw you fixed it, but why not just do as a raw query, in a more traditional way. Your code is not very readable at the moment.

$results = DB::select('select * from `note` where `note_structure_id` = :id and JSON_EXTRACT(LCASE(data), `$._letter`) = :a and JSON_EXTRACT(data, `$._number`) = :number', ['id' => 3, 'a' => 'a', 'number' => 1]);

Upvotes: 1

Related Questions