Doctrine query with orderBy count - sql

I have an Entity "Company" (linked to an "Account") which can have multiple "Tickets".
I want to get the five first companies with the most tickets
I've got this so far but it doesn't work :
public function getByMostTickets($idAccount) {
$qb = $this->createQueryBuilder('c')
->where("c.account = ".$idAccount)
->orderBy("COUNT(c.tickets)", "DESC");
return $qb->getQuery()->getResult();
}
Apparently, it doesn't like that I do the "COUNT" in the orderBy.

Can you try something like this?
$qb = $this->createQueryBuilder('c')
->join("c.tickets", "t")
->where("c.account = :account_id")
->setParameter("account_id", $idAccount)
->groupBy("c.id")
->orderBy("COUNT(t.id)", "DESC");
[EDITED]
sorry this should work... But dump the result to see what this returns...
$qb = $this->createQueryBuilder('c')
->select("c", "COUNT(t.id) as countTickets")
->join("c.tickets", "t")
->where("c.account = :account_id")
->setParameter("account_id", $idAccount)
->groupBy("c.id")
->orderBy("countTickets", "DESC");

Related

multiple joins with the same table in eloquent

Is there some elegant way to write the following query in eloquent? I would like to avoid using the raw query:
results(id, data)
result_filters (id, result_id, filter_id, value)
SELECT * FROM results, result_filters as age, result_filters as followers
WHERE age.result_id = results.id
AND followers.result_id = results.id
AND age.filter_id = 2
AND age.value > 90
AND followers.filter_id = 6
AND followers.value < 10000
If you are using the laravel eloquent
your model relation could be like
model Result:
public function resultFilters()
{
return $this->hasMany('App\ResultFilter');
}
model ResultFilter:
public function result()
{
return $this->belongsTo('App\Result','result_id');
}
try the below code:
$result = Result::find(1);
$data = $result->resultFilter()
->whereIn('filter_id',[2,6])
->whereBetween('value',[90,10000])
->get();
What do you think? It's uses DB::raw but it works
$data = DB::table(DB::raw("results, result_filters as age, result_filters as followers "))
->select(DB::raw("* "))
->where('age.result_id', 'results.id')
->where('followers.result_id', 'results.id')
->where('age.filter_id', 2)
->where('age.value', '<', 90)
->where('followers.filter_id',6)
->where('followers.value','<',10000)
->get();

Doctrine query with ManyToMany relation

I have a simple relation ManyToMany between two entities "article" and "category" (for a blog). I would like to fetch every article with a particular category, but I don't know how to create that query. What I did is :
$query = $em->createQuery(
'SELECT u
FROM SiteBlogBundle:article u
WHERE u.categorie.name = :cat
ORDER BY u.date DESC'
)
->setParameter('cat', '$cateogory')
The line WHERE u.categorie.name = :cat doesn't work. How can I achieve that?
If you are okay with using a query-builder for better readability instead of DQL:
$articles = $em
->getRepository('SiteBlogBundle:Article')
->createQueryBuilder('article')
->leftJoin('article.category', 'category')
->where('category.name = :category_name')
->orderBy('article.date', 'DESC')
->setParameter('category_name', $category->getName())
->getQuery()
->getResult()
;
But i would strongly advise you to put this query into the repository like this:
// ArticleRepository.php
public function findArticlesByCategoryName($name)
{
return $this->createQueryBuilder('article')
->leftJoin('article.category', 'category')
->where('category.name = :category_name')
->orderBy('article.date', 'DESC')
->setParameter('category_name', $name)
->getQuery()
->getResult()
;
}
Then inside your controller just do:
public function getArticles(Category $category)
{
$em = $this->getDoctrine()->getEntityManager();
return $em->
getRepository('SiteBlogBundle:Article')
->findArticlesByCategoryName($category->getName())
;
}

How to get the result of the join operations?

Whenever I tried to execute this sql query in a function module in drupal I am not able to get the results but when I try to execute this in MySQL I can view the result. My code looks like this :
function _get_subject_sub_category() {
$options = array();
$sql = "SELECT father.Subject_Code, child.Subject_Category
FROM {subjects} as child
INNER JOIN {subjects} as father ON (child.Parent_Category = father.Subject_Code
AND child.Level =2 )";
$result = db_query($sql);
foreach ($result as $row) {
$options[$row->father.Subject_Code] = $row->child.Subject_Category;
}
return $options;
}
The error I encountered is in the line $options[$row->father.Subject_Code] = $row->child.Subject_Category;`.
Any help will be highly appreciated.
Try changing this line:
$options[$row->father.Subject_Code] = $row->child.Subject_Category;
To this:
$options[$row->Subject_Code] = $row->Subject_Category;
The name of the table is not in the result. If you need to avoid confusion, you can use alias in your SQL query.
I don't know drupal and don't use php, but I would say :
remove
father. in $row->father.Subject_Code
and
child. in $row->child.Subject_Category
as father and child are just db aliases.

How to get particular column in zend using Left join

I am new to zend framework,
Following is the plain mysql query which takes particular column from table,
SELECT jobs_users.id,jobs_users.first_name from jobs_users left join friends on jobs_users.id=friends.friend_id where friends.member_id=29
I tried with zend to implement the above query like below,
public function getFriendsProfileList($id){
$db = Zend_Db_Table::getDefaultAdapter();
$select = $db->select();
$select->from('jobs_users')
->joinLeft(
'friends',
'jobs_users.id=friends.friend_id',
array('jobs_users.id','jobs_users.first_name','jobs_users.last_name','jobs_users.photo')
)
->where("friends.member_id = ?", $id);
$result = $db->fetchAll($select);
return $result;
}
Here i got result with all column name , not with exact column name which i have given in query.
Kindly help me on this.
Use this instead:
$select->from('jobs_users', array('jobs_users.id','jobs_users.first_name','jobs_users.last_name','jobs_users.photo'))
->joinLeft('friends', 'jobs_users.id=friends.friend_id')
->where("friends.member_id = ?", '20');
You may also try this:
$select = $db->select();
$select->setIntegrityCheck(false);
$select->joinLeft('jobs_users','',array('jobs_users.id','jobs_users.first_name','jobs_users.last_name','jobs_users.photo'));
$select->joinLeft('friends','jobs_users.id=friends.friend_id', array());
$select->where("friends.member_id = ?", $id);
$result = $db->fetchAll($select);
return $result;

how to get last inserted id - zend

I'm trying to get latest inserted id from a table using this code:
$id = $tbl->fetchAll (array('public=1'), 'id desc');
but it's always returning "1"
any ideas?
update: I've just discovered toArray();, which retrieves all the data from fetchAll. The problem is, I only need the ID. My current code looks like this:
$rowsetArray = $id->toArray();
$rowCount = 1;
foreach ($rowsetArray as $rowArray) {
foreach ($rowArray as $column => $value) {
if ($column="id") {$myid[$brr] = $value;}
//echo"\n$myid[$brr]";
}
++$rowCount;
++$brr;
}
Obviously, I've got the if ($column="id") {$myid[$brr] = $value;} thing wrong.
Can anyone point me in the right direction?
An aternative would be to filter ID's from fetchAll. Is that possible?
Think you can use:
$id = $tbl->lastInsertId();
Aren't you trying to get last INSERT id from SELECT query?
Use lastInsertId() or the value returned by insert: $id = $db->insert();
Why are you using fetchAll() to retrieve the last inserted ID? fetchAll() will return a rowset of results (multiple records) as an object (not an array, but can be converted into an array using the toArray() method). However, if you are trying to reuse a rowset you already have, and you know the last record is the first record in the rowset, you can do this:
$select = $table->select()
->where('public = 1')
->order('id DESC');
$rows = $table->fetchAll($select);
$firstRow = $rows->current();
$lastId = $firstRow->id;
If you were to use fetchRow(), it would return a single row, so you wouldn't have to call current() on the result:
$select = $table->select()
->where('public = 1')
->order('id DESC');
$row = $table->fetchRow($select);
$lastId = $row->id;
It sounds like it's returning true rather than the actual value. Check the return value for the function fetchAll