简体   繁体   English

如何在Laravel中搜索奇怪的人物?

[英]How can i search strange characters in Laravel?

I have a problem with the search on my site. 我在我的网站上搜索时遇到问题。 I have a search input to find products by name. 我有一个搜索输入,用于按名称查找产品。 If I type 'leña' (the problem is the strange characters). 如果输入“leña”(问题是奇怪的字符)。

This is in the controller 这是在控制器中

 $termino = $_POST['search']);
 $locale = LaravelLocalization::getCurrentLocale(); //es in this case
 $products = Product::where('title', 'LIKE', "%\"{$locale}\":%{$termino}%");

This is the content of the field 'title' in the database. 这是数据库中“标题”字段的内容。

{"es":"PAN DE LE\u00d1A"}

The search returns 0 results. 搜索返回0个结果。

I am sure the problem is the codification and I don´t know how to resolve it. 我确定问题出在编纂,我不知道该如何解决。

The codification is utf8mb4. 编码为utf8mb4。

Thanks 谢谢

I would simply encode the string before performing the query, eg: 我只是在执行查询之前对字符串进行编码,例如:

// assuming that $termino is a string 
// json_encode should return the unicode representation
$search = json_encode($termino);

// I changed the where condition a bit, 
// but your own condition is also do fine
$products = Product::where('title->'.$locale, 'LIKE', '%'.$search.'%');

The problem does not really lie on non-English characters. 问题并不真正在于非英语字符。 The root issue is that you store a complex data format (JSON) in a single database cell, as opposed to designing your database to hold the individual pieces of data: 根本问题是,您将复杂的数据格式(JSON)存储在单个数据库单元中,而不是将数据库设计为容纳单个数据:

create table product_title (
    product_id int(10) not null,
    locale varchar(2) not null,
    title varchar(200),
    primary key (product_id, locale)
);
insert into product_title (product_id, locale, title) values (1, 'es', 'Leña');
insert into product_title (product_id, locale, title) values (1, 'en', 'Wood');

You have a relational database but you haven't designed it around your data structure, so you cannot use most of its features, inclusing basic stuff like WHERE or ORDER BY . 您有一个关系数据库,但尚未针对数据结构进行设计,因此无法使用其大多数功能,包括WHEREORDER BY类的基本内容。

You can fix the design (please, do) or apply a workaround: 您可以修复设计(请执行)或应用解决方法:

  • If you have a recent MySQL version, you can make the column of JSON type . 如果您使用的是最新的MySQL版本,则可以将列设置为JSON类型
  • You can create two versions of your JSON data and expect that database values do not have mixed cases: 您可以创建两个版本的JSON数据,并期望数据库值没有大小写混合的情况:

     $locale = 'es'; $termino = 'Leña'; $data = [ $locale => ":%{$termino}%" ]; $ascii = json_encode($data); $unicode = json_encode($data, JSON_UNESCAPED_UNICODE); // Use your framework's syntax instead: $sql = 'SELECT * FROM product WHERE title IN (:ascii, :unicode)'; $params = [$ascii, $unicode]; 

Please note there's no sane workaround to use LIKE wildcards too. 请注意,也没有使用LIKE通配符的合理解决方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM