Convert Sql query to sql CodeIgniter - mysql

convert sql query to sql codeigniter
i done try to use this method
How to convert sql query to codeigniter active records
but not working for me...
so i try to post in here
this my sql query
$sql = "SELECT b.id, b.us_id, b.kredit, b.info,u.us_name,
u.us_username, u.us_email, u.us_phone, b.cnt, b.amnt
FROM users u JOIN
(SELECT id, us_id, kredit, info, COUNT(info) cnt, SUM(kredit) amnt
FROM balance_history
GROUP BY info HAVING cnt > 1
) AS b
ON u.us_id = b.us_id
WHERE b.kredit != '0' AND
b.info NOT LIKE '[PERBAIKAN]%' AND
(b.info LIKE 'Transfer saldo%' OR b.info LIKE 'Ket%')
ORDER BY b.id ASC";
thanks before...

If you aren't loaded database globally, you can load it by calling $this->load->database(); The following query may provide the same db call.
$this->db->select('id, us_id, kredit, info, COUNT(info) cnt, SUM(kredit) amnt')
->from('balance_history')
->group_by('info')
->having('cnt > 1');
$subquery = $this->db->get_compiled_select();
$query = $this->db
->select('b.id, b.us_id, b.kredit, b.info,u.us_name,u.us_username, u.us_email, u.us_phone, b.cnt, b.amnt')
->from('users u')
->join('('.$subquery.') b','u.us_id = b.us_id')
->where('b.kredit !=','0', true)
->not_like('b.info', '[PERBAIKAN]', 'after', false, true)
->where('(b.info LIKE "Transfer saldo%" OR b.info LIKE "Ket%")')
->get();

Related

Doctrine oridinal number with mysql (Error: Expected Literal, got '#')

I need to have an oridinal number from mysql database. I found how emulate of row_num in mysql like this:
SET #row=0;
SELECT * FROM (
SELECT (#row:=#row+1) AS no, id, name FROM `attribute` ORDER BY id
) t WHERE name LIKE "%Jo%"
I begin code with:
$this->getEntityManager()->getConnection()->exec("SET #counter = 0");
and I tried:
$this->result = $this->createQueryBuilder('a')
->select('a')
->where($expr->in('att.ordinal_number', $this->createQueryBuilder('att')->
select('(#counter:=#counter+1) AS ordinal_number')->
from(\App\Entity\Attribute::class, 'att')->
orderBy('att.id')->getDQL()))
and I tried:
$this->result = $this->createQueryBuilder('a')
->select('a')
->addSelect('(SELECT (#counter:=#counter+1) AS oridinal_number, id, '
.' name FROM App:Entity:Atrribute ORDER BY id)')
Above give me:
Error: Expected Literal, got '#'
Anybody know how to emulate row_number in doctrine with mysql?
Thanks in advance.
AFAIK there is no direct way to incorporate these DB variables in DQL or query builder, you will need to execute Native SQL and then use ResultSetMapping class to map the result of query to your entity
SQL
SELECT *
FROM (
SELECT (#row:=#row+1) AS no,
id,
name
FROM `attribute` ,(SELECT #row:=0) t
ORDER BY id
) t WHERE name LIKE "%Jo%"
Resultset Mapping
$rsm = new ResultSetMapping;
$rsm->addEntityResult('Attribute', 'a');
$rsm->addFieldResult('a', 'id', 'id');
$rsm->addFieldResult('a', 'name', 'name');
$rsm->addScalarResult('no', 'no');
$query = $this->_em->createNativeQuery('SELECT *
FROM (
SELECT (#row:=#row+1) AS no,
id,
name
FROM attribute ,(SELECT #row:=0) t
ORDER BY id
) t WHERE name LIKE ?',$rsm);
$query->setParameter(1, '%Jo%');
$users = $query->getResult();

Convert SQL query to yii2?

Until now I have been using a SQL query in yii2 which was working fine locally but as soon as I deploy it to the server it shows
I have tried changing it to yii query since its a proper implementation below
$query = $connection->createCommand("SELECT a.name_of_flight, a.time_of_flight, (a.no_of_passenger - b.cnt) as avail, a.no_of_passenger FROM flight_schedule a LEFT JOIN (SELECT flight_time, COUNT(id) AS cnt FROM book_eticket WHERE flight_date='$date' AND company_name = '$comp_name' GROUP BY flight_time) b ON a.id = b.flight_time")->queryAll();
to
$query = (new \yii\db\Query());
$query
->select('a.name_of_flight, a.time_of_flight, (a.no_of_passenger - b.cnt) as avail, a.no_of_passenger')
->from('flight_schedule a')
->leftJoin('flight_time', ('COUNT(id) AS cnt FROM book_eticket'))
->where(array('and', 'flight_date=2016-6-29', 'company_name = Team5'))
->groupBy(['flight_time b','ON a.id = b.flight_time']);
$command = $query->createCommand();
$query = $command->queryAll();
but I get an error:
Can anybody help me find out the problem? Thanks in advance
First screen says about access issues. Second - that operands like date and team is not string. That is wrong. Can you quote them?

How to convert RIGHT LEFT functions to codeigniter active record

I have a query like this:
SELECT RIGHT(id, 1) id_root
FROM user
WHERE LENGTH(id) = 3
and LEFT(id, 1) = '0'
And how to convert that's query to active record in codeigniter.
My problem is with syntax RIGHT( id, 1 ) and also at LEFT(id,1)='0'
$result_arr = $this->db
->select("RIGHT(id, 1) id_root", FALSE)
->from("user")
->where(
array("LENGTH(id)"=> 3, "LEFT(id, 1) =" => 0)
)->get()
->result_array();
Or you can simply use $this->db->query("You SQL");
$query = "SELECT RIGHT(id, 1) id_root
FROM user
WHERE LENGTH(id) = ?
and LEFT(id, 1) = ? ";
$result_arr = $this->db->query($query, array(3, 0))->result_array();
You can produce your query like this
$this->db->from('user');
$this->db->select('RIGHT(id, 1) id_root',false);
$this->db->where('LENGTH(id)',3,true);
$this->db->where('LEFT(id, 1) =','0',true);
$results=$this->db->get()->result();
Remember if you want to use mysql function at your select query which may break mysql syntax by codeigniter use false as 2nd parameter so that codeigniter does not protect/covert your fields.
Same for where, if you want to use mysql function or other function which may break mysql syntax by CI use 3rd parameter as true so that codeigniter does not convert your fields.
See details at documentation
Simplest way to get any query result using $this->db->query('YOUR_QUERY') But I prefer using CI Active record's functions.
$query = "SELECT RIGHT(id, 1) id_root
FROM user
WHERE LENGTH(id) = 3
and LEFT(id, 1) = '0'";
$result = $this->db->query($query);

Eloquent query building complex query to get unique records searching for an ID in 2 different columns in same table

I'm migrating a project to Laravel 4 and I am stuck with a quite complex query, which I'd like to migrate into a proper Eloquent query.
I have a table that contains chat messages, called chat_messages with a representing Model Chatmessage
The table contains a sender and a receipient column with a user id linking to the users table and User Model.
The query to get a list with all user IDs of all chat partners in raw SQL on the old version of the application is as follows:
$sql_allChatPartners = "SELECT DISTINCT chatPartner
FROM ( SELECT * FROM (
SELECT cm_receipient AS chatPartner, cm_sent_at
FROM chat_messages WHERE cm_sender = '".$me->userID."'
UNION
SELECT cm_sender AS chatPartner, cm_sent_at
FROM chat_messages WHERE cm_receipient = '".$me->userID."'
) whateva ORDER BY whateva.cm_sent_at DESC ) other";
Sorry for naming the "fake" tables whateva and other :-)
Could anyone put me in the right direction to do this with Eloquent Querybuilder?
It is important that I get the list of chatPartner IDs in the correct order, where the last chat message has been exchanged as first chatPartner. And the chatPartner where longest inactivity was in the chat as last entry.
This is what I got so far in my User Model...
public function allopenchats(){
$asSender = Chatmessage::where('sender', $this->id)->select('receipient as chatPartner, created_at');
$asBoth = Chatmessage::where('receipient', $this->id)->select('sender as chatPartner, created_at')
->union($asSender)->orderBy('created_at', 'desc')->get();
}
I renamed the columns cm_receipient to receipient, cm_sender to sender and sent_at to created_at in the new database for the new version
Your help would be very much appreciated!
You sql may change to:
SELECT IF (cm_receipient = '10', cm_sender, IF (cm_sender = '10',cm_receipient, 'no')) AS chatPartner, cm_sent_at
FROM chat_messages
WHERE cm_receipient = '10' OR cm_sender = '10'
GROUP BY chatPartner
HAVING chatPartner != 'no'
order by cm_sent_at DESC
In orm:
Chatmessage::where('sender','=',$this->id)
->orWhere('receipient','=',$this->id)
->select(DB::raw('IF (receipient = '.$this->id.', sender, IF (sender = '.$this->id.',receipient, 'no' )) AS chatPartner'), 'created_at')
->groupBy('chatPartner')
->having('chatPartner', '!=', 'no')
->orderBy('created_at', 'desc')
->get();
Thanks very much to Vitalik_74, I wouldn't have come that far without him.
Here is now the final query, although its not in ORM, but it is working fine and gives me the result I need.
$result = DB::select("SELECT *
FROM (
SELECT IF( receipient = '".$this->id."', sender, IF( sender = '".$this->id."', receipient, 'no' ) ) AS chatPartner, created_at
FROM chatmessages
WHERE receipient = '".$this->id."'
OR sender = '".$this->id."'
HAVING chatPartner != 'no'
ORDER BY created_at DESC
)whateva
GROUP BY whateva.chatPartner
ORDER BY whateva.created_at DESC");
if there is someone out there who can do this query with the Laravel Query Builder, I would be happy to see it. For now I'll leave it like this.

Converting MYSQL to Codeigniter

I am trying to convert a MYSQL query to codeigniter and going no wheres real fast. I am trying to convert this query
$conn->prepare("SELECT `id`,`song`,`artist`,`album`,`track`,`mix_name`,`date` FROM `podcasts` where mix_number = (SELECT MAX(mix_number) FROM podcasts) order by track asc");
This is in my model:
//$where = '(SELECT MAX(mix_number)from podcasts)';
$this->db->select('id,song,artist,album,track,mix_name,date, link');
//$this->db->where('mix_number', '(SELECT MAX(mix_number)from podcasts)');
$this->db->order_by('track', 'asc');
$query = $this->db->get('podcasts');
return $query->result();
My problem area is in the where statement. When I comment out the where statement I get the data. Obviously not in the manner I want it.
I am doing it this way becuase my next query(s) will be
("SELECT `id`,`song`,`artist`,`album`,`track`,`mix_name`,`date` FROM `podcasts` where mix_number = **(SELECT MAX(mix_number) FROM podcasts) - 1** order by track asc")
And on down to (SELECT MAX(mix_number) FROM podcasts) - 3
Any thoughts on the proper way of writing the where statement? Thank you for yout time.
Set the third argument of where() to false to prevent CI from altering the string you pass in to the second argument, then you can do the subquery:
return $this->db
->select('id,song,artist,album,track,mix_name,date, link')
->where('mix_number', '(SELECT MAX(mix_number) from podcasts)', false)
->order_by('track', 'asc')
->get('podcasts')
->result();
https://www.codeigniter.com/userguide2/database/active_record.html$this->db->where() accepts an optional third parameter. If you set it to FALSE, CodeIgniter will not try to protect your field or table names with backticks.
For me this produces the following query:
SELECT `id`, `song`, `artist`, `album`, `track`, `mix_name`, `date`, `link`
FROM (`podcasts`)
WHERE mix_number = (SELECT MAX(mix_number) from podcasts) ORDER BY `track` asc
If you are not too particular about using CodeIgniter's Active Record syntax, you can simply use your query as is:
$sql = "SELECT `id`,`song`,`artist`,`album`,`track`,`mix_name`,`date` FROM `podcasts` where mix_number = (SELECT MAX(mix_number) FROM podcasts) order by track asc";
$this->db->query($sql);
and then use $query->result() to get your results.