Reputation: 5084
I have a Entity in Symfony for Videos. Lets say the db looks like this:
id: int
name: varchar
uploader: int (User Entity)
video_mp4: varchar
param1: int
param2: int
param3: int
I'd like to load similar videos. Similar means:
Actually I'd like to order them by the most matchings (meaning a video uploaded by the same user and with same param1 + param3 should be more important then one where just param2 is matching) something like ORDER BY mostMatches DESC
any ideas how to achive that
For this I'd use this query (yes I know that "OR" isn't good for the DB, sugestions welcome ;))
I created in my Entity class a function that looks like this: ($q is a QueryBuilder)
public function getRelated($q, $limit = 6) {
$uploader = $this->getUploader()->getId();
$param1 = $this->getParam1();
$param2 = $this->getParam2();
$param3 = $this->getParam3();
$q->select('e')
->from('MyBackendBundle:Video','e')
->where('e.id != ?0')
->andWhere('e.uploader = ?1 OR e.param1 = ?2 OR e.param2 = ?3 OR e.param3 = ?4');
if ($limit > 0) {
$q->setMaxResults($limit);
}
$q->setParameters(array(
$this->id,
$uploader,
$param1,
$param2,
$param3
));
return $q->getQuery()->getResult();
}
Two questions:
Upvotes: 0
Views: 1073
Reputation: 13340
You can just sum all these matchings:
SELECT
*,
(CAST(e.uploader = ?1 AS UNSIGNED)
+ CAST(e.param1 = ?2 AS UNSIGNED)
+ CAST(e.param2 = ?3 AS UNSIGNED)
+ CAST(e.param3 = ?4 AS UNSIGNED)
) AS matches_count
FROM video
ORDER BY matches_count DESC
Upvotes: 1