How to do left join in doctrine with entity manager? - mysql

I have a query in sql like that
select * from films F left join ballot_films BF on F.FilmId=BF.FilmId where BF.FilmId is null;
i want to convert it into doctrine, i m new with doctrine and don't know so much, i searched and tried a lot but didn't get any success,please help me to how can i do that query in doctrine using entity managaer, million ton thanks in advance.

Assuming you have the correct mappings between films and ballot_films, the following should work:
// Get the entity manager
$em = $this->getDoctrine()->getManager("em");
// Get your film repository
$filmRepository = $em->getRepository("Film");
// Create the initial query builder
$query = $filmRepository->createQueryBuilder("films");
// Set your query criteria
$query->select("films")
->leftJoin("ballot_films")
->where("ballot_films.FilmId = null");
// Get the query results
$films = $query->getQuery()->getResult();
This will give you all films where ballot_films.FilmId is null.

Related

return result from table that not existed on another table in codeignator

I've constructed two tables: one to list the services and another to link the service to each department.
Table 1 contains the columns [s id,s name]. [s_id,s_name].
-- The Services table, records all services for all departments. [1,Install Windows 10],[2,print Payslip].
Table 2 : services_assignments consist of columns [ss_id,ss_s_id_ss_d_id].
-- services_assignments matching the services with departments.
I need to return the service that "NOT" matched for the department example.
i tried to use JOIN with Where conditions in selection but not result as the following code.
function get_services_for_assign(){ // for assigmnets
$this->db->select('*');
$this->db->from('services');
if($this->uri->segment('2')) {
$this->db->join('services_assignments','services.sr_id = services_assignments.ss_s_id','left');
$this->db->where_not_in('services_assignments.ss_d_id',$this->uri->segment('2'));
}
//$this->db->where('sr_display','1');
$data=$this->db->get();
return $data->result();
}
On the other hand, I attempted to write it manually as seen below.
function get_services_for_assign(){ // for assigmnets
$dep=$this->uri->segment('2');
$query = "SELECT sr.sr_id FROM services AS sr WHERE sr.sr_id = (SELECT sa.ss_s_id FROM services_assignments AS sa WHERE sa.ss_d_id = 1)";
$this->db->query($query);
$data=$this->db->get();
return $data->result();
}
and I encountered the following error; I discovered numerous results that were similar to my problem, but I couldn't solve it.
A Database Error Occurred
Error Number: 1096
No tables used
SELECT *
Filename: C:/xampp/htdocs/townteam/system/database/DB_driver.php
Line Number: 691
I need your help to return the results services that were not used by the other department.
You have not stated which version of CodeIgniter you are using or what the expected behaviour is when no department id is passed.
This should work in both CI3 and CI4. If using CI4, you should probably use prepared statements. I could not find documentation on passing parameters into a multi-condition join with CI so I have written the query out in full.
$sql = <<<'SQL'
SELECT s.*
FROM services s
LEFT JOIN services_assignments sa
ON s.sr_id = sa.ss_s_id
AND sa.ss_d_id = ?
WHERE sa.ss_s_id IS NULL
AND s.sr_display = 1
SQL;
$this->db->query($sql, [$this->uri->segment('2')]);

Yii 2 JSON_VALUE result as join condition in Active Record

Example we have Table A and B.
In table A we have data field with some json data.
How to be build Active Record relation using JSON_VALUE condition?
In plain sql it would look like
SELECT * FROM A
LEFT JOIN B ON B.id = JSON_VALUE(A.data, '$.paramName')
You could use a findBySql method
$sql = "SELECT * FROM A
LEFT JOIN B ON 'B.id = JSON_VALUE(A.data, " . $paramName . ")";
$model = YourModel::findBySql($sql)->all();
As far as i could find framework it self dosnot support sql function execution result as join relation. For now best way for me is to execute subqueries and use populateRelation method. ofcouse if youll find better way i would be glad to know.

Convert MYSQL query into Laravel Eloquent ORM

My query is :
SELECT * FROM drivers INNER JOIN vehicle ON drivers.vehicle_id = vehicle.id INNER JOIN cartype ON vehicle.cartype_id = cartype.id WHERE drivers.status = "free" AND vehicle.cartype_id = 1
Convert this query into laravel eloquent query .
I've tried harder but can't achieve !
Since we don't know what models and relationship between them you have - here is pure Query Builder request (pure translation of your sql, even if join with cartype table is redundant):
$result = DB::table("drivers")
->where("drivers.status", "free")
->join("vehicle", "drivers.vehicle_id", "=", "vehicle.id")
->join("cartype", "vehicle.cartype_id", "=", "cartype.id")
->where("vehicle.cartype_id", 1)->get()
Source: documentation, API page.

INNER JOIN Results from Select Statement using Doctrine QueryBuilder

Can you use Doctrine QueryBuilder to INNER JOIN a temporary table from a full SELECT statement that includes a GROUP BY?
The ultimate goal is to select the best version of a record. I have a viewVersion table that has multiple versions with the same viewId value but different timeMod. I want to find the version with the latest timeMod (and do a lot of other complex joins and filters on the query).
Initially people assume you can do a GROUP BY viewId and then ORDER BY timeMod, but ORDER BY has no effect on GROUP BY, and MySQL will return random results. There are a ton of answers out there (e.g. here) that explain the problem with using GROUP and offer a solution, but I am having trouble interpreting the Doctrine docs to find a way to implement the SQL with Doctrine QueryBuilder (if it's even possible). Why don't I just use DQL? I may have to, but I have a lot of dynamic filters and joins that are much easier to do with QueryBuilder, so I wanted to see if that's possible.
Sample MySQL to Reproduce in Doctrine QueryBuilder
SELECT vv.*
FROM view_version vv
#inner join only returns where the result sets overlap, i.e. one record
INNER JOIN (
SELECT MAX(timeMod) maxTimeMod, viewId
FROM view_version
GROUP BY viewId
) version ON version.viewId = vv.viewId AND vv.timeMod = version.maxTimeMod
#join other tables for filter, etc
INNER JOIN view v ON v.id = vv.viewId
INNER JOIN content_type c ON c.id = v.contentTypeId
WHERE vv.siteId=1
AND v.contentTypeId IN (2)
ORDER BY vv.title ASC;
Theoretical Solution via Query Builder (not working)
I am thinking that the JOIN needs to inject a DQL statement, e.g.
$em = $this->getDoctrine()->getManager();
$viewVersionRepo = $em->getRepository('GutensiteCmsBundle:View\ViewVersion');
$queryMax = $viewVersionRepo->createQueryBuilder()
->addSelect('MAX(timeMod) AS timeModMax')
->addSelect('viewId')
->groupBy('viewId');
$queryBuilder = $viewVersionRepo->createQueryBuilder('vv')
// I tried putting the query in a parenthesis, to no avail
->join('('.$queryMax->getDQL().')', 'version', 'WITH', 'vv.viewId = version.viewId AND vv.timeMod = version.timeModMax')
// Join other Entities
->join('e.view', 'view')
->addSelect('view')
->join('view.contentType', 'contentType')
->addSelect('contentType')
// Perform random filters
->andWhere('vv.siteId = :siteId')->setParameter('siteId', 1)
->andWhere('view.contentTypeId IN(:contentTypeId)')->setParameter('contentTypeId', $contentTypeIds)
->addOrderBy('e.title', 'ASC');
$query = $queryBuilder->getQuery();
$results = $query->getResult();
My code (which may not match the above example perfectly) outputs:
SELECT e, view, contentType
FROM Gutensite\CmsBundle\Entity\View\ViewVersion e
INNER JOIN (
SELECT MAX(v.timeMod) AS timeModMax, v.viewId
FROM Gutensite\CmsBundle\Entity\View\ViewVersion v
GROUP BY v.viewId
) version WITH vv.viewId = version.viewId AND vv.timeMod = version.timeModMax
INNER JOIN e.view view
INNER JOIN view.contentType contentType
WHERE e.siteId = :siteId
AND view.contentTypeId IN (:contentTypeId)
ORDER BY e.title ASC
This Answer seems to indicate that it's possible in other contexts like IN statements, but when I try the above method in the JOIN, I get the error:
[Semantical Error] line 0, col 90 near '(SELECT MAX(v.timeMod)': Error: Class '(' is not defined.
A big thanks to #AdrienCarniero for his alternative query structure for sorting the highest version with a simple JOIN where the entity's timeMod is less than the joined table timeMod.
Alternative Query
SELECT view_version.*
FROM view_version
#inner join to get the best version
LEFT JOIN view_version AS best_version ON best_version.viewId = view_version.viewId AND best_version.timeMod > view_version.timeMod
#join other tables for filter, etc
INNER JOIN view ON view.id = view_version.viewId
INNER JOIN content_type ON content_type.id = view.contentTypeId
WHERE view_version.siteId=1
# LIMIT Best Version
AND best_version.timeMod IS NULL
AND view.contentTypeId IN (2)
ORDER BY view_version.title ASC;
Using Doctrine QueryBuilder
$em = $this->getDoctrine()->getManager();
$viewVersionRepo = $em->getRepository('GutensiteCmsBundle:View\ViewVersion');
$queryBuilder = $viewVersionRepo->createQueryBuilder('vv')
// Join Best Version
->leftJoin('GutensiteCmsBundle:View\ViewVersion', 'bestVersion', 'WITH', 'bestVersion.viewId = e.viewId AND bestVersion.timeMod > e.timeMod')
// Join other Entities
->join('e.view', 'view')
->addSelect('view')
->join('view.contentType', 'contentType')
->addSelect('contentType')
// Perform random filters
->andWhere('vv.siteId = :siteId')->setParameter('siteId', 1)
// LIMIT Joined Best Version
->andWhere('bestVersion.timeMod IS NULL')
->andWhere('view.contentTypeId IN(:contentTypeId)')->setParameter('contentTypeId', $contentTypeIds)
->addOrderBy('e.title', 'ASC');
$query = $queryBuilder->getQuery();
$results = $query->getResult();
In terms of performance, it really depends on the dataset. See this discussion for details.
TIP: The table should include indexes on both these values (viewId and timeMod) to speed up results. I don't know if it would also benefit from a single index on both fields.
A native SQL query using the original JOIN method may be better in some cases, but compiling the query over an extended range of code that dynamically creates it, and getting the mappings correct is a pain. So this is at least an alternative solution that I hope helps others.

Select query in spring hibernate in spring mvc

Hi i am writing an spring mvc, employee application using mysql database,hibernate annotations and jsp . The database contains one table "Empdata" where empid is primary key.And there is a column "team" in "Empdata".I want to select employees in a specific team, example all the details of employees in "Team1".Here i can perform delete and edit operations in the application. For delete operation i am using
sessionfactory.getCurrentSession().createQuery("DELETE FROM Resource WHERE empid=" +resource.getEmpId()).executeUpdate();
query.I know the command line query for select is
SELECT * FROM EmpData WHERE EMPLTEAM ="Team1"
I want to know how to convert this query into hibernate?
please help,thanks in advance..
Query query = session.createQuery("from Resource where emplteam = :team");
query.setParameter("team", "Team1");
List list = query.list();
emplteam should be the property of your class Resource , not your database column's name.
I guess it is simple using HQL .
String hql = "FROM Resource E WHERE E.emplteam = team1";
Query query = session.createQuery(hql);
List results = query.list();
Hope this helps
Note: Keywords like SELECT , FROM and WHERE etc. are not case sensitive but properties like table and column names are case sensitive in HQL.
have you tried using criteria api?
Criteria crit = sessionFactory.getCurrentSession()
.createCriteria(EmpData.class).add(Restrictions.eq("EMPLTEAM", "teamxxx");
List<EmpData> result = crit.list();
For example
Query query = session.createQuery("from Student where name=:name");
query.setParameter("name", "Raj");
In your case i guess the Entity name is Empdata(The object that represent the table)
And the field in the object is team(That has getter and setter in object)
Query query = session.createQuery("from Empdata where team=:teamParam");
query.setParameter("teamParam", "team1");