how to join between two databases in codeigniter - php

I'm having a problem joining these two databases using codeigniter, I tried it using mysql and it worked.
can someone can convert it to codeigniter
This is my code
SELECT DATE_FORMAT(FROM_UNIXTIME(ex.extime), '%Y-%m-%d') as `export_report`, u.username as `Username`, ex.qdesc as `Search_Performed`,
ex.to as `Number_of_records_exported`, ex.format as `Format`
FROM cone.users u
INNER JOIN igdata.export_status as ex
ON u.id = ex.uid
WHERE DATE_FORMAT(FROM_UNIXTIME(ex.extime), '%Y-%m-%d') = '{$dateToday}'
ORDER BY u.username ASC
I also put this in my constructor
private $cone_read;
private $ixdata;
function __construct()
{
// Call the Model constructor
parent::__construct();
$this->cone_read = $this->load->database('cone_read', TRUE);
$this->ixdata = $this->load->database('cone_us', TRUE);
}

try this:
$this->db->select("DATE_FORMAT(FROM_UNIXTIME(ex.extime), '%Y-%m-%d') as export_report, u.username as Username, ex.qdesc as Search_Performed, ex.to as Number_of_records_exported, ex.format as Format");
$this->db->from('cone.users u');
$this->db->join('igdata.export_status as ex', 'u.id = ex.uid');
$this->db->where("DATE_FORMAT(FROM_UNIXTIME(ex.extime), '%Y-%m-%d') = '$dateToday'");
$this->db->order_by("u.username", "asc");
$query = $this->db->get();

Related

Add additional fields into doctrine result (DTO)

Im trying to get the best rated movies by average from my database and hydrate them nicely into a DTO with doctrine so i can work well later with it and integrate them e.g. into my api with api platform.
I already managed to get it work with a raw SQL query but i cannot manage to get it work with hydration into a DTO with doctrine.
namespace App\Repository;
use App\Entity\Movie;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
class MovieRepository extends ServiceEntityRepository
{
public function findBestRated()
{
$sql = "
SELECT m.*, AVG(Cast(r.rating as Decimal)) AS avg_rating, COUNT(r.id) AS count_rating
FROM `movie` m
JOIN rating r ON r.movie_id = m.id
GROUP BY m.id
ORDER BY avg_rating DESC
LIMIT 10
";
$connection = $this->getEntityManager()->getConnection();
$statement = $connection->prepare($sql);
$result = $statement->executeQuery();
return $result->fetchAllAssociative();
}
}
I would like to use a DTO like below:
namespace App\Dto;
use App\Entity\Movie;
class RatedMovie
{
public Movie $movie;
public float $averageRating;
public int $ratingCount;
public function __construct(Movie $movie, float $averageRating, int $ratingCount)
{
$this->movie = $movie;
$this->averageRating = $averageRating;
$this->ratingCount = $ratingCount;
}
}
I found some information on https://geek-week.imtqy.com/articles/en496166/index.html, but still i cannot get the hydration running. I already tried with ResultSetMapping and ResultSetMappingBuilder and a native doctrine query. With ResultSetMappingBuilder i can kind of simulate my raw sql query but the result is still an associative array and not mapped into the RatedMovie DTO.
public function findBestRated()
{
$rsm = new ResultSetMappingBuilder($this->getEntityManager());
$rsm->addScalarResult('id', 'movieId');
$rsm->addScalarResult('name', 'movieName');
$rsm->addScalarResult('avg_rating', 'averageRating', Types::FLOAT);
$rsm->addScalarResult('count_rating', 'countRating', Types::INTEGER);
$sql = "
SELECT m.*, AVG(r.rating) AS avg_rating, COUNT(r.id) AS count_rating
FROM `movie` m
JOIN rating r ON r.name_id = m.id
GROUP BY m.id
ORDER BY avg_rating DESC
LIMIT 10
";
$query = $this->getEntityManager()->createNativeQuery($sql, $rsm);
return $query->getResult();
}
I cannot get it running with newObjectMappings or the kind of strange syntax SELECT NEW DepartmentSalary(d.dept_no, avg_salary) FROM ... from the linked article. Any ideas?

Group By Three columns doesn't work in CodeIgniter

I needed a result with Group By three columns and the SQL works perfectly without any issue. I'm facing the issue when I use it in the CodeIgniter framework; it doesn't execute the query. My Code and SQL are as follows.
Code
$this->db->select(['trk.userid AS user_id', 'scr.course AS course_id'])
->from('mdl_scorm scr')
->join('mdl_scorm_scoes_track trk', 'scr.id = trk.scormid', 'inner')
->join('mdl_course_modules mcs', 'mcs.instance = scr.id', 'inner')
->where_in('trk.value', ['completed','incomplete','passed'])
->group_by(['scr.course', 'trk.userid', 'trk.scormid'])
->order_by('trk.userid', 'DESC');
SQL
SELECT `trk`.`userid` AS user_id, `scr`.`course` AS course_id
FROM (`mdl_scorm` scr)
INNER JOIN `mdl_scorm_scoes_track` trk ON `scr`.`id` = `trk`.`scormid` INNER JOIN `mdl_course_modules` mcs ON `mcs`.`instance` = `scr`.`id`
WHERE `trk`.`value` IN ('completed', 'incomplete', 'passed')
GROUP BY `scr`.`course`, `trk`.`userid`, `trk`.`scormid`
ORDER BY `trk`.`userid` DESC LIMIT 0,100;
This works fine when the group_by has only two columns, like,
->group_by(['scr.course', 'trk.userid'])
What could be the reason?
In codeigniter group_by() works with two fields only.
$this->db->group_by()
Permits you to write the GROUP BY portion of your query:
$this->db->group_by(array("title", "date")); // Produces: GROUP BY title, date
CI 3 group_by()
Edit 01
$query=$this->db->query("
SELECT `trk`.`userid` AS user_id, `scr`.`course` AS course_id
FROM `mdl_scorm` scr
INNER JOIN `mdl_scorm_scoes_track` trk
ON `scr`.`id` = `trk`.`scormid`
INNER JOIN `mdl_course_modules` mcs
ON `mcs`.`instance` = `scr`.`id`
WHERE `trk`.`value` IN ('completed', 'incomplete', 'passed')
GROUP BY `scr`.`course`, `trk`.`userid`, `trk`.`scormid`
ORDER BY `trk`.`userid`
DESC LIMIT 0,100;");
$result = $query->result_array();
return $result;
Consider a raw query in the model.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class xyz_model extends CI_Model{
function __construct()
{
// Call the Model constructor
parent::__construct();
}
function get_this_thing($month,$year)
{ $myQuery="SELECT `trk`.`userid` AS user_id, `scr`.`course` AS course_id
FROM `mdl_scorm` scr
INNER JOIN `mdl_scorm_scoes_track` trk
ON `scr`.`id` = `trk`.`scormid`
INNER JOIN `mdl_course_modules` mcs
ON `mcs`.`instance` = `scr`.`id`
WHERE `trk`.`value` IN ('completed', 'incomplete', 'passed')
GROUP BY `scr`.`course`, `trk`.`userid`, `trk`.`scormid`
ORDER BY `trk`.`userid`
DESC LIMIT 0,100;";
$query = $this->db->query($myQuery);
$result = $query->result();
return $result;
}
}
You can also pass an array of multiple values as well:
$this->db->group_by(array("title", "date")); // Produces: GROUP BY title, date
Source link
use result array instead of the result like
return $query->result_array();

selecting a colum from joined tabels in database Codeigniter

I am trying to select column name level_name from table levels,
which contains level_id and level_name,
for a user to know what is their level,
The table of users named as users and contain a level_id and user_id,
but I get this error ->
Column 'level_id' in on clause is ambiguous
SELECT `level_name`
FROM `levels`
JOIN `users` ON `level_id` = `level_id` WHERE `user_id` = '9'
here it is the code in the model
public function level_ownprofile($user_id)
{
$this->db->select('level_name');
$this->db->from('levels');
$this->db->join('users', 'level_id = level_id');
$this->db->where('user_id', $user_id);
$query = $this->db->get();
return $query;
}
thanks in advance :)
Change the query to
SELECT `level_name`
FROM `levels` l
JOIN `users` u ON `u`.`level_id` = `l`.`level_id`
WHERE `user_id` = '9'
if you like the table name aliasing method, it is shorter and easier to read.
Or
SELECT `level_name`
FROM `levels`
JOIN `users` ON `users`.`level_id` = `levels`.`level_id`
WHERE `user_id` = '9'
If you prefere to use the full table name everywhere.
Because both tables contain a column with the name level_id the query analyser need to know which one you are addressing.
In codeigniter try
public function level_ownprofile($user_id)
{
$this->db->select('level_name');
$this->db->from('levels l');
$this->db->join('users u', 'u.level_id = l.level_id');
$this->db->where('user_id', $user_id);
$query = $this->db->get();
return $query;
}
Select l.level_name
FROM levels l
JOIN users u
ON u.level_id = l.level_id
and u.user_id = '9'
public function level_ownprofile($user_id)
{
$this->db->select('level_name');
$this->db->from('levels');
$this->db->join('users', 'levels.level_id = users.level_id');
$this->db->where('user_id', $user_id);
$query = $this->db->get();
return $query;
}
public function level_ownprofile($user_id)
{
$this->db->select('l.level_name');
$this->db->from('levels as l');
$this->db->join('users as u', 'l.level_id = u.level_id');
$this->db->where('l.user_id', $user_id);
$query = $this->db->get();
return $query->results();
}

How to build a Docterine Inner Join Query in Symfony

Im working on a Symfony project and I want to create Doctrine Query for this SQL.
USER table :
columns -
NICK_NAME
REVIEWS table:
columns -
USER_ID
, REVIEW,
CREATED_AT
Thank you
SELECT
`USER`.NICK_NAME,
REVIEWS.REVIEW,
REVIEWS.CREATED_AT
FROM
REVIEWS
INNER JOIN `USER` ON REVIEWS.USER_ID = `USER`.ID
WHERE
REVIEWS.MOVIE_ID = 625
GROUP BY
REVIEWS.USER_ID
I tried something like this
$q = Doctrine_Query::create()
->select("u.NICK_NAME,r.REVIEW,r.CREATED_AT")
->from('REVIEWS r')
->innerJoin('`USER` ON REVIEWS.USER_ID = `USER`.ID')
->where('REVIEWS.MOVIE_ID = 625')
->groupBy('REVIEWS.USER_ID');
and got this:
500 | Internal Server Error | Doctrine_Exception Couldn't find class `USER`
Without using complex DQL in Symfony you can use simple SQL.
Try this function in the controller where you want to run the DQL.
function getUserReviews($params) {
$query = "SELECT REVIEWS.REVIEW, `USER`.NICK_NAME, REVIEWS.CREATED_AT FROM REVIEWS INNER JOIN `USER` ON REVIEWS.USER_ID = `USER`.ID WHERE REVIEWS.MOVIE_ID ='".$params."'";
return Doctrine_Manager::getInstance()->getCurrentConnection()->fetchAssoc($query);
}
You Should Specify Entity name not table name in DQL like this YourBundleName:EntityName
Use it like this:
$q = Doctrine_Query::create()
->select("u.NICK_NAME,r.REVIEW,r.CREATED_AT")
->from('REVIEWS r')
->innerJoin('YourBundleName:EntityName ON REVIEWS.USER_ID = `USER`.ID')
->where('REVIEWS.MOVIE_ID = 625')
->groupBy('REVIEWS.USER_ID');
Alternative Solution if above solution doesn’t work:
$q = Doctrine_Query::create()
->select("u.NICK_NAME,r.REVIEW,r.CREATED_AT")
->from('REVIEWS r')
->innerJoin('YourBundleName:EntityName', 'USER_ID')
->where('REVIEWS.MOVIE_ID = 625')
->groupBy('REVIEWS.USER_ID');
If that doesn't work, use Inner join in following manner:
->InnerJoin('YourBundleName:Entity', '<alias>', Expr\Join::ON, $qb->expr()->eq('IDENTITY(<alias.<clummn_name>)', '<comapring_column>'))
inner Join from Doctrine2 Documentation:
Example -
$qb->innerJoin('u.Group', 'g', Expr\Join::WITH, qb->expr()->eq('u.status_id', '?1'))
$qb->innerJoin('u.Group', 'g', 'WITH', 'u.status = ?1')
$qb->innerJoin('u.Group', 'g', 'WITH', 'u.status = ?1', 'g.id')
innerJoin Method Prototype:
innerJoin($join, $alias, $conditionType = null, $condition = null, $indexBy = null);
Find More Here
Hope this will help you.

CakePHP, special select

I will be blunt, I need the model list to be built from this special select:
SELECT * FROM posts p WHERE p.user_id IN
(SELECT u.id FROM users u, following f
WHERE u.id = f.followee_id AND f.follower_id = $id)
ORDERED BY p.created
LIMIT $limit;
Is it possible to put this as a function into the model? I am quite new to CakePHP, I must admit.
I can't use the find functions here because then the posts wouldn't be properly "mixed".
Yes, you can add your own method to the Model class that will execute the query you write.
But don't forget to sanitize your input (it is not done automatically when you write your own queries) and to add table prefixes.
App::import('Sanitize');
class YourModel extends AppModel {
public function specialSelect($id, $limit) {
$id = Sanitize::paranoid($id); // or use (int) to convert it to integer
$limit = Sanitize::paranoid($limit);
return $this->query(
'SELECT * FROM '.$this->tablePrefix.'posts p WHERE p.user_id IN '.
'(SELECT u.id FROM '.$this->tablePrefix.'.users u, '.$this->tablePrefix.'.following f '.
'WHERE u.id = f.followee_id AND f.follower_id = '.$id.') '.
'ORDER BY p.created LIMIT '.$limit
);
}
}

Categories