SQL Raw data query - zend-framework2

Hi I am trying to query some data like this
$sql = "SELECT *
FROM company";
$stmt = $this->getDbAdapter()->query($sql, \Zend\Db\Adapter\Adapter::QUERY_MODE_EXECUTE);
if ($stmt instanceof \Zend\Db\ResultSet\ResultSet) {
foreach ($stmt as $row) {
$entities[] =$row;
}
}
But I get an 500 Internal server error, Is there something wrong with this code?
I have done this one an it work fine.
$sql = "SELECT company.*,address_home.*,address_billing.*, T1.*
FROM company AS company
INNER JOIN address AS address_home ON company.address_id_fk = address_home.address_id
INNER JOIN address AS address_billing ON company.billing_address_id_fk = address_billing.address_id
INNER JOIN (SELECT company_id_fk,
max(case when company_role_id_fk = '1' then 'true' end) isClient,
max(case when company_role_id_fk = '2' then 'true' end) isSupplier
FROM company_role_company_maps AS crcm
WHERE crcm.company_id_fk = $id
GROUP BY company_id_fk) AS T1
ON(company.company_id = T1.company_id_fk)
WHERE company.company_id = $id";
$resultset = $this->getDbAdapter()->query($sql, \Zend\Db\Adapter\Adapter::QUERY_MODE_EXECUTE);
$current = $resultset->current()->getArrayCopy();
But for some reason when I do the loop i get the error.
I try this to see If I cud catch something.
$sql = "SELECT *
FROM company";
$stmt = $this->getDbAdapter()->query($sql, \Zend\Db\Adapter\Adapter::QUERY_MODE_EXECUTE);
if ($stmt instanceof \Zend\Db\ResultSet\ResultSet) {
try{
foreach($stmt as $row) {
var_dump($row);
}
}catch(\Exception $e){
var_dump($e->getMessage());
}
}
But I just got the Internal server error message (There is a problem with the resource you are looking for, and it cannot be displayed.)

Related

Typeorm subquery add select

I am new for using typeorm and this is the second time I am confused with typeorm, I have the following query :
SELECT t1.a,t1.b,t2.a
(SELECT TOP 1 t1.a
FROM table1 t1
WHERE t1.b = t2.a
ORDER BY t1.a DESC
) AS MaxT1
FROM Table1 t1
INNER JOIN Table2 t2 ON t1.a = t2.a
I tried this:
let query = await getManager()
.createQueryBuilder(Bid, 'bid')
.select([
'l.ID_anv_Lot',
'l.LotNumber',
'w.WineryName',
'bid.BidAmount',
'bid.ProxyBidAmount',
'er.ID_Contact'
])
.addSelect(Table1, t1)
.innerJoin(Lot, 'l', 'l.lotNumber = bid.lotNum AND l.paddleNumber = bid.paddleNumber')
but the result is all of the rows on table1
This Example may help you to perform sub query execution:
const posts = await connection.getRepository(Post)
.createQueryBuilder("post")
.where(qb => {
const subQuery = qb.subQuery()
.select("usr.name")
.from(User, "usr")
.where("usr.registered = :registered")
.getQuery();
return "post.title IN " + subQuery;
})
.setParameter("registered", true)
.orderBy("post.id")
.getMany();
You can use subselects in SELECT statements:
let query = await this.createQueryBuilder('t1')
.select()
.innnerJoin('t1.t2', 't2', 't1.a = t2.a')
.addSelect(subQuery => {
return subQuery
.select('_t1.a')
.from(Table1, '_t1')
.where('_t1.b = t2.a');
}, 'MaxT1')
.getRawMany()
You can find more here: https://orkhan.gitbook.io/typeorm/docs/select-query-builder

Linq Query to fetch data using non entity object

I'm trying to fetch the record from 3 tables by comparing the user Logged in name
Here is my code:
public ActionResult MeritList() //departmental merit listed students details with status 1
{
var username= HttpContext.Session["UserName"];
List<StdListModel> model = new List<StdListModel>();
var query = (from s in Context.tblStdDetails
join e in Context.tblStdEnrollments on s.ID equals e.StdReg_ref_id
//join d in Context.tblDepartments on e.Depart_ref_id equals d.ID
where s.Status == '1' && e.tblDepartment.DepartName == username
select new StdListModel
{
ID = s.ID,
Name = s.Name,
FatherName = s.FatherName,
CNIC = s.CNIC,
FormNo = s.FormNo,
DiaryNo = s.DiaryNo,
Status = s.Status
}).ToList();
foreach(var item in query)
{
model.Add(new StdListModel()
{
ID=item.ID,
Name=item.Name,
FatherName=item.FatherName,
CNIC=item.CNIC,
FormNo=item.FormNo,
DiaryNo=item.DiaryNo
});
}
return View(model);
}
Also Tried this Query
var query = (from s in Context.tblStdDetails
join e in Context.tblStdEnrollments on s.ID equals e.StdReg_ref_id
join d in Context.tblDepartments on e.Depart_ref_id equals d.ID
where s.Status == '1' && d.DepartName.Equals(username)
select new StdListModel
{
ID = s.ID,
Name = s.Name,
FatherName = s.FatherName,
CNIC = s.CNIC,
FormNo = s.FormNo,
DiaryNo = s.DiaryNo,
Status = s.Status
}).ToList();
But it does not return anything model=0, query =0, the database has right values and I don't get any error either.
please check username with tolower() and trim function.
e.tblDepartment.DepartName.ToLower().Trim() == username.ToLower().Trim()
or
e.tblDepartment.DepartName.ToLower().Trim().equals(username.ToLower().Trim())
I got the problem. It is in
s.Status == '1'
I just changed it into
s.Status == 1
and it works fetch the data from the database.

how to fit complex mysql query into zf2

i am unable to fit my query into zf2 query, i can fit simple join query but i can not write for more complex sub queries.
please help me to do this.
SELECT `created_date` FROM `salesmodule_discussed_topic` dt WHERE dt.`meeting_id` IN(
SELECT ma.`meeting_id` FROM `salesmodule_meeting_agent` ma WHERE ma.`agent_id`=30547
)
public function getLastmeetingdate() {
$select = new Select();
$select->from(array('dt' => 'salesmodule_discussed_topic'));
$select->columns(array('created_date'));
$select->where(array('ma.`agent_id` => 30547));
$resultSet = $this->tableGateway->selectWith($select);
return $resultSet->buffer();
}
The previous example is bad because has an sql injections. You need make a subquery using Select.
public function getLastmeetingdate() {
$subQuery = new Select();
$subQuery->from(array('ma' => 'salesmodule_meeting_agent'));
$subQuery->columns(array('meeting_id'));
$subQuery->where(array('ma.agent_id' => 30547));
$select = new Select();
$select->from(array('dt' => 'salesmodule_discussed_topic'));
$select->columns(array('created_date'));
$select->where->in('dt.meeting_id', $subQuery);
return $this->tableGateway->selectWith($select);
}
public function fetchAllSubQuery($id = '') {
$columns = array("*");
$where = "main_booking_id IN (SELECT
b1.`main_booking_id`
FROM
`booking_sector` b1
WHERE b1.`connected_booking_id` = '$id' OR b1.`main_booking_id` = '$id') ";
$resultSet = $this->tableGateway->select(function (Select $select) use ($where,$columns) {
$select->where($where);
$select->columns($columns);
});
$resultSet->buffer();
// $resultSet->next();
return $resultSet;
}

Zend Framework 2 Sql Select with OR and AND

I want to make this query using Zend\Db\Sql\Select:
SELECT table1.* FROM table1
INNER JOIN table2 ON table1.columnA = table2.columnB
INNER JOIN table3 ON table1.columnC = table3.columnD
WHERE (table2.column2 = 2 or table3.column3 = 3) and table1.column1 = 1
ORDER BY table1.columnE ASC LIMIT 1
I have this code so far:
/*#var $db Adapter */
$db = $this->getServiceLocator()->get('db');
$sql = new Sql($db);
$select = $sql->select();
$select->from('table1');
$select->join('table2','table1.columnA = table2.columnB',array());
$select->join('table3','table1.columnC = table3.columnD',array());
$select->where(array('table2.column2' => 2, 'table2.column3' => 3), Predicate\PredicateSet::OP_OR);
$select->where(array('table1.column1' => 1),Predicate\PredicateSet::OP_AND);
$select->order('table1.columnE ASC');
$select->limit(1);
$statement = $sql->prepareStatementForSqlObject($select);
$resultSet = $statement->execute();
But doesn't works, because produce this one (without the "(" and ")" for the OR):
SELECT table1.* FROM table1
INNER JOIN table2 ON table1.columnA = table2.columnB
INNER JOIN table3 ON table1.columnC = table3.columnD
WHERE table2.column2 = 2 or table3.column3 = 3 and table1.column1 = 1
ORDER BY table1.columnE ASC LIMIT 1
What can I do?
from the top of the head using Where fluent interface:
$select->where
->nest
->equalTo('table2.column2', 2)
->or
->equalTo('table2.column3', 3)
->unnest
->and
->equalTo('table1.column1', 1);
I would do something like:
$where = new \Zend\Db\Sql\Where();
$where
->nest()
->equalTo('table2.column2', 2)
->or
->equalTo('table2.column3', 3)
->unnest()
->and
->equalTo('table1.column1', 1);
$select->where($where)
Just because this way your $select keep being an implementation of Zend\Db\Sql\SqlInterface
while doing
$select->where
->nest
will return an instance of a Zend Sql operator. Which is not bad but then you can't just do
$statement = $sql->prepareStatementForSqlObject($select);
$resultSet = $statement->execute();

LINQ convert DateTime to string

List<Post> list =
(
from c in db.TitleComments
join t in db.Titles on c.TitleId equals t.Id
join u in db.Users on c.UserId equals u.Id
where t.Id == _titleId && c.Date > time
orderby c.Date descending
select new Post { Username = u.Username, PostingDate = c.Date.ToString(), Data = c.Comment }
).ToList();
The code above causes exception on the convertion of date to string, PostingDate = c.Date.ToString(). Any ideas how to get around this?
Exception error:
{"LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression."}
linq is trying to convert date to string using sql but since there is no ToString() method in sql it can't convert it, this behavior is by design - Joakim
In other words, return the date itself and convert it to a string after it executes on SQL side:
(
select new { Username = u.Username,
PostingDate = c.Date
[...]
})
.ToList() // runs on SQL and returns to the application
.Select(o => // is not generating a SQL, it is running on the app
new Post { Username = o.Username,
PostingDate = o.PostingDate.ToString(),
[...]
})
You can remedy your problem by projecting into an anonymous type, and then at a later step project into Post after the data has already been returned from the DB.
(from ....
select new { /* stuff */, Date = c.Date })
.AsEnumerable()
.Select(p => new Post { /* stuff */, PostingDate = p.Date.ToString() })
.ToList();
However, given that you have a property called PostingDate, the original source being a date, I would recommend your revise your object to actually keep the value as a DateTime instead of a string.
I dont think this can be done in a direct way.
var list =
select new Post { Username = u.Username, PostingDate = SqlFunctions.StringConvert(c.Date), Data = c.Comment }
from
(from c in db.TitleComments
join t in db.Titles on c.TitleId equals t.Id
join u in db.Users on c.UserId equals u.Id
where t.Id == _titleId && c.Date > time
orderby c.Date descending).AsEnumerable()
).ToList();
Also with EF4 you can try something like this:
List<Post> list =
(
from c in db.TitleComments
join t in db.Titles on c.TitleId equals t.Id
join u in db.Users on c.UserId equals u.Id
where t.Id == _titleId && c.Date > time
orderby c.Date descending
select new Post { Username = u.Username, PostingDate = SqlFunctions.DateName(c.Date), Data = c.Comment }
).ToList();

Resources