Laravel中的JSON给出了错误SQLSTATE [42000]:检查与MariaDB服务器对应的手册

问题描述 投票:0回答:2

我试图从laravel Where JSON获取数据库中的数据。但它给出了一个错误。我添加了这样的数据。

$event = new Event;
$event->scores = json_encode([['user_ids' => [1,2,3,4],'score' => 15]]);
$event->save();

当我想在数据库中返回数据时。

Event::where('scores->score',15)->get()

显示此错误:

SQLSTATE [42000]:语法错误或访问冲突:1064 SQL语法中有错误;检查与MariaDB服务器版本对应的手册,以便在'>'$附近使用正确的语法。“score”'=?'在第1行(SQL:select * from`events`,其中`scores` - >'$。“得分”'= 15)

我的MariaDB版本是10.2.1

php mysql laravel mariadb
2个回答
1
投票

数组和JSON转换

在您的活动模型上,您需要添加

class Event extends Model {
      protected $casts = ['scores'=>'array'];
// ...
}

然后在保存数据时

$event = new Event;
// you had what appeared to be an extra array, that could cause the issue?
$event->scores = ['user_ids' => [1,2,3,4],'score' => 15]; 
$event->save();

然后,只要列类型为TEXT或JSON(MySQL的新版本),数据将自动保存为JSON。

请参阅Laravel文档中的数组和JSON转换:qazxsw poi

然后检索:

https://laravel.com/docs/5.5/eloquent-mutators#array-and-json-casting

以下是JSON Where子句Event::where('scores->score', '15')->get(); 的相关文档


0
投票

再一次,对于你在问什么感到很困惑。可能有助于查看表的结构或预期的SQL应该是什么样的。

如果您尝试根据存储在表中的JSON字符串中包含的值返回行...那么您需要执行类似的操作...

https://laravel.com/docs/5.5/queries#json-where-clauses

或者沿着这些方向的东西...... ->whereRaw("JSON_CONTAINS(score, '[15]' )")->get();

© www.soinside.com 2019 - 2024. All rights reserved.