【问题标题】:Doctrine search simple_array field that has matching keywords具有匹配关键字的教义搜索 simple_array 字段
【发布时间】:2021-10-09 10:24:37
【问题描述】:

我有一个具有 simple_array 字段 keywords 的实体。例如,我有值为drama, adventure, action 和另一个drama, sci-fi 的实体。 我想提供action, adventure,并返回第一个实体。因为它有匹配的关键字。

如果我尝试使用 IN 数组进行搜索,它仅在实体关键字字段只有一个条目时才有效。

$query->andWhere("g.keyword IN (:keywords)")
    ->setParameter('keywords', $keywords);

我的问题是,查询应该是什么样子,能够通过多个关键字进行搜索,而字段有多个关键字。

【问题讨论】:

  • 因此在数据库中它们存储为序列化字符串。喜欢"a:3:{i:0;s:5:"drama";i:1;s:9:"adventure";i:2;s:6:"action";}"

标签: doctrine-orm doctrine


【解决方案1】:

如果你的 prop 声明如下:

/**
* 
* @ORM\Column(name="keyword", type="simple_array")
*/
private $keyword;

没有简单的方法。 simple_array 每次保存/更新(插入/更新)到数据库时,只需将 php-array 数据自动序列化为序列化字符串将其从序列化字符串自动反序列化为 php-每次读取时数组(SELECT)

据我所知,没有解决方案使用 MySQL 和学说。 不过,PostgreSQL 有一些很好的存储序列化数据的特性,但我不确定。

我唯一能想到的就是对您提供的每个关键字都使用 LIKE。因此,如果您提供action, adventure SQL 将是

SELECT * FROM `your_table` WHERE keyword LIKE '%action%' AND keyword LIKE '%adveture%' 

用学说(QueryBuilder)得到这个

foreach($keywords as $idx => $singleKeyword) {
   // note, that you have to put '%' at the start and at the end and use it as param
   // LIKE %:keyword% -> would not work. 
   $query->andWhere('g.keyword LIKE :keyword_'.$idx)->setParameter('keyword_'.$idx, '%'.$singleKeyword.'%' );
}

但只有当所有提供的关键字都匹配时,您才会得到结果。

【讨论】:

  • 是的,我想你是对的,我做了类似但更丑陋的事情,我的 DQL 看起来像 AND (g.keyword LIKE '%adventure%' OR g.keyword LIKE '%action%')
【解决方案2】:

我不知道你在做什么,但如果可能的话,改变你的 DB-Structure。为您的关键字制作一个单独的表格,在此表格中每条记录代表一个关键字并引用您的主要实体。

如果这样做,使用它更容易工作和构建查询。

SELECT * FROM MainEntity LEFT JOIN Keywords ON Keywords.MainEntityId = MainEntity.Id
WHERE Keywords.Value IN (Value1, Value2, Value3)

【讨论】:

    猜你喜欢
    • 2012-09-20
    • 1970-01-01
    • 2014-12-17
    • 1970-01-01
    • 2015-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多