数据库:
id | name | // ...
====================
1 | London |
2 | Paris |
3 | Moscow |
4 | New York |
// ...
文字:
This is a big city. I live in this town.
I like the name of city. 'New York' is very cool.
However, I have to go to Moscow this summer.
// ...
数据库中有很多记录。
文本以多种语言编写。
我想获取与文本相关的记录。
在这种情况下,我想获得“纽约”和“莫斯科”的记录。
我正在使用 Doctrine2 ORM 和 DQL。
而我的数据库一般是mysql。
是否可以通过使用 DQL 来实现?
更新
城市实体:id、名称、人口创建日期等...
id | name | population | // ...
====================================
1 | London | 1,2448,3938|
2 | Paris | 1,8759,4844|
3 | Moscow |12,8450,3748|
4 | New York | 8,4795,8558|
// ...
文章实体:id, body, author, date_created etc...
id | body | // ...
============================================================
1 | This is a big city. I live in this town. |
| I like the name of city. |
| 'New York' is very cool. |
| However, I have to go to Moscow this summer.|
| // ... |
2 | We bought a house in London. //... |
3 | I go to Canada this weekend. //... |
4 | Weather in Africa today is too bad. //... |
// ...
无论是从文件还是数据库中获取的文本都是好的。
public function findOneById($id)
{
$query = $this->getEntityManager()->createQuery('
SELECT a, u
FROM MyArticleBundle:Article a
LEFT JOIN a.author u
WHERE a.id = :id
')
->setParameter('id', $id);
return $this->try_catch($query);
}
or
$article = file_get_contents('example.txt');
然后我把它带到显示器上。
{{ article }} or {{ article.body }} etc...
此时如何获取与本文相关的城市数据?
是否需要复杂的数据库配置?
文本和实体(在本例中为“城市”数据)没有关联。
是否有可能获取出现在文本或字符串中的数据?
例如:SELECT c FROM MyExampleBundle:City c WHERE c.name appear in ({$text});
虽然我知道这个例子是不可能的,但我想知道是否有一种方法可以很容易地像 DQL 中的那样。
最佳答案
在这种情况下,我想获取“纽约”和“莫斯科”的记录。
所以你需要使用 like()
function使用 %
字符。 %
将充当通配符,例如 A%
将选择所选字段以 A
开头的每一行。 %A%
将选择包含 A
的每一行。
public function findArticlesFromTowns($town_1, $town_2)
{
$qb = $this->createQueryBuilder('u');
$buffer = $qb
->select('a, u')
->leftJoin('a.author', 'u')
->where(
$qb->expr()->andX(
$qb->expr()->like('a.body',
$qb->expr()->literal('%'.$town_1.'%')),
$qb->expr()->like('a.body',
$qb->expr()->literal('%'.$town_2.'%'))
)
)
;
$q = $buffer->getQuery();
return $q->getResult();
}
$town_1
和 $town_2
分别是纽约和莫斯科。通过使用 andX()
,查询将选择 body
字段包含 New York 和 莫斯科。
关于mysql - 我想通过DQL获取与文本相关的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23029146/