symfony and DQL - sql

i have :
public function findTodasLasCompras($usuario_id)
{
$em = $this->getEntityManager();
$dql = 'SELECT v, o, t
FROM OfertaBundle:Venta v
JOIN v.oferta o
JOIN o.tienda t
WHERE v.usuario = :id
ORDER BY v.fecha DESC';
$consulta = $em->createQuery($dql);
$consulta->setParameter('id', $usuario_id);
$result = $consulta->getResult();
return $consulta->getResult();
}
and when i execute it fails with it's error:
ContextErrorException: Notice: Undefined index: Cupon\OfertaBundle\Entity\Oferta in C:\wamp\www\sympony\vendor\doctrine\orm\lib\Doctrine\ORM\Internal\Hydration\ObjectHydrator.php line 477
in C:\wamp\www\sympony\vendor\doctrine\orm\lib\Doctrine\ORM\Internal\Hydration\ObjectHydrator.php line 477
at ErrorHandler->handle('8', 'Undefined index: Cupon\OfertaBundle\Entity\Oferta',
help! please! Thanks

Try to tranform your 'JOIN' to 'LEFT JOIN'.
If an usario exists well with id 8, maybe he is not linked to oferta or tienda, so the jointure return nothing, but left join keep usario instance.

First of all, replace this:
$result = $consulta->getResult();
return $consulta->getResult();
with this:
$result = $consulta->getResult();
return $result;
Maybe you should reinstall Symphony, it seems something is broken.

Related

symfony2 - Doctrine - How to do a multiple select with a count and group by

In Symfony2 and Doctrine I would like to execute a query that returns a count and a group by.
Here's what I've tried. This is the SQL I want to run:
SELECT `terrain_id` , COUNT( * )
FROM `Partie`
WHERE 1 =1
GROUP BY `terrain_id`
With my entity:
class Partie
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #ORM\ManyToOne(targetEntity="Gp\UserBundle\Entity\User",
inversedBy="parties", cascade={"persist"})
* #ORM\JoinColumn(nullable=false)
*/
private $user;
/**
* #ORM\ManyToOne(targetEntity="Gp\JeuxBundle\Entity\Terrain")
*/
private $terrain;
This is my PartieRepository
public function getTest(\Gp\UserBundle\Entity\User $user){
return $this->createQueryBuilder('p')
->select('count(p), p.terrain')
->where('p.user = :user')
->setParameter('user', $user)
->groupBy('r.terrain')
->getQuery()
->getResult();
}
This is the error I get:
[Semantical Error] line 0, col 19 near 'terrain FROM': Error:
Invalid PathExpression. Must be a StateFieldPathExpression.
You'll probably want to go with a Native Query
$sql = "SELECT terrain_id as terrain,
count(*) AS count "
."FROM Partie "
."GROUP BY terrain_id;";
$rsm = new ResultSetMapping;
$rsm->addScalarResult('terrain', 'terrain');
$rsm->addScalarResult('count', 'count');
$query = $this->_em->createNativeQuery($sql, $rsm);
return $query->getResult();
Just add in any having / where clauses as needed.
The following is my result:
Array
(
[0] => Array
(
[terrain] =>
[count] => 7
)
[1] => Array
(
[terrain] => 1
[count] => 5
)
[2] => Array
(
[terrain] => 2
[count] => 1
)
)
The lack of terrain in the first array is due to null terrain_id.
EDIT
OP has unexpected results, so here are some troubleshooting steps:
1) Try a var_dump($query->getSQL()); right before the return statement, and run the SQL directly against your DB. If this produces incorrect results, examine the query and alter the $sql as appropriate.
2) If #1 produces correct results, try a var_dump($query->getResult()); right before the return statement. If this produces correct results, something is going on deeper in your code. It's time to look at why terrain is being filtered. It may be as simple as removing or changing the alias in SQL and addScalarResult.
3) Try an even simpler function:
$sql = "SELECT distinct(terrain_id) FROM Partie;";
$rsm = new ResultSetMapping;
$rsm->addScalarResult('terrain_id', 'terrain_id');
$query = $this->_em->createNativeQuery($sql, $rsm);
var_dump($query->getSQL());
var_dump($query->getResult());
return $query->getResult();
This error occurs on this line : select('count(p), p.terrain') where you are trying to use p alias that doesn't exist anymore. The select method override the default alias of the createQueryBuilder(). To avoid this, use addSelect instead or specify clearly the from method.
Try this :
public function getTest(\Gp\UserBundle\Entity\User $user){
return $this->createQueryBuilder('p')
->addSelect('count(p), p.terrain')
->where('p.user = :user')
->setParameter('user', $user)
->groupBy('r.terrain')
->getQuery()
->getResult();
}
or this :
public function getTest(\Gp\UserBundle\Entity\User $user){
return $this->createQueryBuilder('p')
->select('count(p), p.terrain')
->from('YourBundle:YourEntity', 'p')
->where('p.user = :user')
->setParameter('user', $user)
->groupBy('r.terrain')
->getQuery()
->getResult();
}
How to execute a raw Query with count and group by:
Hook onto your manager and make a new connection:
$manager = $this->getDoctrine()->getManager();
$conn = $manager->getConnection();
Create your query and fetchAll:
$result= $conn->query(
'select count(p.id) foobar, p.myid from foobartable p group by p.myid'
)->fetchAll();
Get the data out of result like this:
$this->appendStringToFile("first row foobar is: " . $result[0]['foobar']);

Codeigniter Joining Tables - Passing Parameters

I'm attempting to join two tables while using codeigniter. I've done this same SQL query writing regular SQL. When I attempt to do the same in codeigniter, I keep getting errors. I'm not quite sure what I'm doing wrong. What do you guys think I'm doing wrong?
My function in model_data.php
function getJoinInformation($year,$make,$model)
{
//$this->db->distinct();
// here is where I need to conduct averages but lets just work on extracting info.
// from the database and join tables.
$this->db->select('*');
$this->db->from('tbl_car_description');
$this->db->join('tbl_car_description', 'd.id = p.cardescription_id');
$this->db->where('d.year', $year);
$this->db->where('d.make', $make);
$this->db->where('d.model', $model);
$result = $this->db->get();
/*
$query = $this->db->get_where('tbl_car_description',
array(
'year' => $year,
'make' => $make,
'model' => $model
)
);
if($query->num_rows()) return $query->result();
return null;
*/
}
My error message
A Database Error Occurred
Error Number: 1066
Not unique table/alias: 'tbl_car_description'
SELECT * FROM (`tbl_car_description`) JOIN `tbl_car_description` ON `d`.`id` = `p`.`cardescription_id` WHERE `d`.`year` = '2006' AND `d`.`make` = 'Subaru' AND `d`.`model` = 'Baja'
Filename: C:\wamp\www\_states\system\database\DB_driver.php
Line Number: 330
Here is the code written in SQL and it's working great. I want to do the something in codeigniter but I'm confused as to how. Any help would be much appreciated. Thanks everyone.
$sql_2 = mysql_query("SELECT ROUND(AVG(p.value),1) AS AvgPrice, ROUND(AVG(p.mileage),1) AS AvgMileage
FROM tbl_car_description d, tbl_car_prices p
WHERE (d.id = p.cardescription_id)
AND (d.year = '".$year."')
AND (d.make = '".$make."')
AND (d.model = '".$model."')
AND (p.approve = '1')");
Your CI query references the same table twice, which I assume is a typo. However, you only need include your table alias with the table name in your Active Record call:
//$this->db->distinct();
$this->db->select('*');
$this->db->from('tbl_car_description d');
$this->db->join('tbl_car_prices p', 'd.id = p.cardescription_id');
$this->db->where('d.year', $year);
$this->db->where('d.make', $make);
$this->db->where('d.model', $model);
$result = $this->db->get();
Couple issues: You need to include your table aliases and your join should have the name of the second table ...
$this->db->from('tbl_car_description AS d');
$this->db->join('tbl_car_prices AS p', 'd.id = p.cardescription_id');

Codeigniter: from sql to activerecord, what is the wrong?

I want to try change my sql code to active record, here is the original code and active record try. And the error message. Please tell me where is my wrong? Thanks.
SELECT `emlakilan`.`id`, `emlakdurum`.`durum`,`emlaktip`.`tip`,`semtler`.`semt`,`emlakilan`.`fiyat`,`emlakilan`.`tarih`,`resim`.`r1` FROM ucburcak.`emlakilan`
INNER JOIN `semtler` ON `emlakilan`.`semtId` = `semtler`.`semtid`
INNER JOIN `emlaktip` ON `emlakilan`.`emlakTipId` = `emlaktip`.`id`
INNER JOIN `emlakdurum` ON `emlakilan`.`emlakDurumId` =`emlakdurum`.`id`
LEFT JOIN `resim` ON `emlakilan`.`resimId` = `resim`.`id`
WHERE `emlakdurumId`=3 ORDER BY `emlakilan`.`id` DESC LIMIT 4;
//and here active record function
public function kucuk_ilan($durum ='3') // $durum:1=>tümü 2=>kiralık 3=>satılık 4=>takas
{
$query = $this->db->select('emlakilan.id, emlakdurum.durum, emlaktip.tip, semtler.semt, emlakilan.fiyat, emlakilan.tarih, resim.r1')
->from('emlakilan')
->join('semtler','emlakilan.semtId' === 'semtler.semtid','inner')
->join('emlaktip','emlakilan.emlakTipId'==='emlaktip.id','inner')
->join('emlakdurum','emlakilan.emlakDurumId'==='emlakdurum.id','inner')
->join('resim','emlakilan.resimId'==='resim.id','left')
->where('emlakdurumId'===$durum)
->order_by('emlakilan.id','desc')
->limit(4);
$query = $this->db->get('emlakilan');
return $query->result_array();
}
And, error message:
Error Number: 1066
Not unique table/alias: 'emlakilan'
SELECT emlakilan.id, emlakdurum.durum, emlaktip.tip, semtler.semt, emlakilan.fiyat, emlakilan.tarih, resim.r1 FROM (emlakilan, emlakilan) INNER JOIN semtler ON INNER JOIN emlaktip ON INNER JOIN emlakdurum ON LEFT JOIN resim ON WHERE 0 IS NULL ORDER BY emlakilan.id desc LIMIT 4
Filename: C:\Program Files\EasyPHP-12.1\www\3burcak\system\database\DB_driver.php
Line Number: 330
Thanks for help.
So 1. remove the 'from' line
2. the joins where wrong
try this:
public function kucuk_ilan($durum ='3') // $durum:1=>tümü 2=>kiralık 3=>satılık 4=>takas
{
$query = $this->db->select('emlakilan.id, emlakdurum.durum, emlaktip.tip, semtler.semt, emlakilan.fiyat, emlakilan.tarih, resim.r1')
->from('emlakilan')
->join('semtler','emlakilan.semtId = semtler.semtid','inner')
->join('emlaktip','emlakilan.emlakTipId = emlaktip.id','inner')
->join('emlakdurum','emlakilan.emlakDurumId = emlakdurum.id','inner')
->join('resim','emlakilan.resimId = resim.id','left')
->where('emlakdurumId', $durum)
->order_by('emlakilan.id','desc')
->limit(4);
$query = $this->db->get('emlakilan');
return $query->result_array();
}

createQueryBuilder IN clause

I´m working with Symfony2 and I need to execute this SQL for example:
select detformacion.* from detformacion
left join formacion
on detformacion.formacion_id = formacion.id
left join detcurso
on formacion.id = detcurso.formacion_id
where detcurso.id IN ('143','144');
For that, I have this in my Repository:
public function getSeleccion() {
$em = $this->getEntityManager();
$query = $em->createQueryBuilder()
->select('d')
->from('GitekUdaBundle:Detformacion', 'd')
->leftJoin('d.formacion', 'f')
->leftJoin('f.detcursos', 'det')
->where('det.id = :miarray')
->setParameter('miarray',array('143','144'))
->getQuery()
;
return $query->getResult();
}
I tried with ->where('det.id IN :miarray') but I´m getting errors all the time.
Any help or clue?
thanks in advance.
UPDATE: The problem is setting the parameters.
Missing parentheses after the IN operator :
->where('det.id IN (:miarray)')
->setParameter('miarray', array('143','144'))

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;