I have this query
SELECT
arl_kind,
IF (tof_art_lookup.arl_kind = 2, tof_suppliers.sup_brand, tof_brands.bra_brand) AS brand,
arl_display_nr
FROM
tof_art_lookup
LEFT JOIN
tof_brands
ON
bra_id = arl_bra_id
INNER JOIN
tof_articles
ON
tof_articles.art_id = tof_art_lookup.arl_art_id
INNER JOIN
tof_suppliers
ON
tof_suppliers.sup_id = tof_articles.art_sup_id
WHERE
arl_art_id = #art_id
AND arl_kind IN (3)
ORDER BY
arl_kind,
bra_brand,
arl_display_nr limit 100;
when I execute this on phpmyadmin or in any software that has sql comand capabilities everything works and the output is as i should.
The problem appears when I try to insert this in codeigniter, and my main probles is with the if statement, I tried to insert it like this
return $query = $this->db
->SELECT('
arl_kind,
IF (tof_art_lookup.arl_kind = 2, tof_suppliers.sup_brand, tof_brands.bra_brand) AS brand,
arl_display_nr
FROM
tof_art_lookup
LEFT JOIN
tof_brands
ON
bra_id = arl_bra_id
INNER JOIN
tof_articles
ON
tof_articles.art_id = tof_art_lookup.arl_art_id
INNER JOIN
tof_suppliers
ON
tof_suppliers.sup_id = tof_articles.art_sup_id
WHERE
arl_art_id = #art_id
AND arl_kind IN (3)
ORDER BY
arl_kind,
bra_brand,
arl_display_nr limit 100')
->get();
and second option like that
return $query = $this->db
->select('ARL_KIND, IF (tof_art_lookup.arl_kind = 2, tof_suppliers.sup_brand, tof_brands.bra_brand) AS brand,ARL_DISPLAY_NR')
->from('tof_art_lookup')
->join('tof_brands','bra_id = arl_bra_id','LEFT')
->join('tof_articles','tof_articles.art_id = tof_art_lookup.arl_art_id','INNER')
->join('tof_suppliers','tof_suppliers.sup_id = tof_articles.art_sup_id','INNER')
->where('ARL_ART_ID',$id)
->where_in('ARL_KIND',array('3'))
//->where('A.ARL_DISPLAY','0')
->group_by('arl_kind','bra_brand','arl_display_nr')
->get();
both of them work but partialy without the second select option the one with the if.
Can anyone help me to fix this.
I believe your code should look like this
return $query = $this->db
->select('arl_kind, IF(tof_art_lookup.arl_kind = 2, tof_suppliers.sup_brand, tof_brands.bra_brand) AS brand,ARL_DISPLAY_NR', FALSE)
->from('tof_art_lookup')
->join('tof_brands', 'bra_id = arl_bra_id', 'LEFT')
->join('tof_articles', 'tof_articles.art_id = tof_art_lookup.arl_art_id', 'INNER')
->join('tof_suppliers','tof_suppliers.sup_id = tof_articles.art_sup_id', 'INNER')
->where('arl_art_id', $id)
->where_in('arl_kind', array('3'))
->order_by('arl_kind','bra_brand','arl_display_nr')
->limit(100)
->get();
Note: second parameter of select() method is set to FALSE and order_by() is used instead of group_by() as in your original query.
use like this
$query_string = "SELECT
arl_kind,
IF (tof_art_lookup.arl_kind = 2, tof_suppliers.sup_brand, tof_brands.bra_brand) AS brand,
arl_display_nr
FROM
tof_art_lookup
LEFT JOIN
tof_brands
ON
bra_id = arl_bra_id
INNER JOIN
tof_articles
ON
tof_articles.art_id = tof_art_lookup.arl_art_id
INNER JOIN
tof_suppliers
ON
tof_suppliers.sup_id = tof_articles.art_sup_id
WHERE
arl_art_id = #art_id
AND arl_kind IN (3)
ORDER BY
arl_kind,
bra_brand,
arl_display_nr limit 100";
$query=$this->db->query($query_string);
if ($query->num_rows () > 0) {
return $query->result_array ();
} else {
return FALSE;
}
Related
I have a raw sql query which i run using yii2 Yii::$app->db->createCommand() but then i wonder i how i can use yii's method of writing queries to actualize the same thing.
$m = "SELECT p.basic_plan_amt AS basic,p.premium_plan_amt AS premium,p.daju_plan_amt AS daju,c.name
AS country FROM price p LEFT JOIN country c ON p.country_id = c.id WHERE p.country_id = " .$country_id;
though the above query works well and provide expected result, but then how can i write the same query using the below format
$model = \backend\models\Price::find()->select([p.basic_plan_amt AS basic,p.premium_plan_amt AS
premium,p.daju_plan_amt AS daju,c.name
AS country])->where(['country_id' => $country_id])->all();
Below are the examples of query in yii hope it will help you More reference
Relation Model
$model = User::find()
->with('comments')
->all();
foreach ($model as $user) {
// get data from relation model
$comments = $user->comments;
......
foreach($comments as $comment){
........
}
}
joinWith()
Sample 1:
$model = User::find()
->joinWith('comments')
->all();
Sample 2:
$model = User::find()
->joinWith('comments')
->orderBy('tbl_comments_id.id, tbl_user.id')
->all();
innerJoinWith()
$model = User::find()
->innerJoinWith('comments', false)
->all();
// equivalent to the above
$model = User::find()
->joinWith('comments', false, 'INNER JOIN')
->all();
Join()
JOIN_TYPE = INNER JOIN, LEFT OUTER JOIN, RIGHT OUTER JOIN, FULL OUTER JOIN etc
Syntax
$query = new Query;
$query ->select(['SELECT COLUMNS'])
->from('TABLE_NAME_1')
->join( 'JOIN_TYPE',
'TABLE_NAME_2',
'TABLE_NAME_2.COLUMN =TABLE_NAME_1.COLUMN'
);
$command = $query->createCommand();
$data = $command->queryAll();
Sample 1:
$query = new Query;
$query ->select([
'tbl_user.username AS name',
'tbl_category.categoryname as Category',
'tbl_document.documentname']
)
->from('tbl_user')
->join('LEFT OUTER JOIN', 'tbl_category',
'tbl_category.createdby =tbl_user.userid')
->join('LEFT OUTER JOIN', 'tbl_document',
'tbl_category.cid =tbl_document.did')
->LIMIT(5) ;
$command = $query->createCommand();
$data = $command->queryAll();
Output Query
SELECT `tbl_user`.`username` AS `name`, `tbl_category`.`categoryname` AS `Category`
FROM `tbl_user`
LEFT OUTER JOIN `tbl_category` ON tbl_category.createdby =tbl_user.userid
LEFT OUTER JOIN `tbl_document` ON tbl_category.cid =tbl_document.did
LIMIT 5
leftJoin()
Sample 1:
$query = new Query;
$query ->select(['tbl_user.username AS name', 'tbl_category.type as Category'])
->from('tbl_user')
->leftJoin('tbl_category', 'tbl_category.createdby = tbl_user.userid')
->limit(2);
$command = $query->createCommand();
$data = $command->queryAll();
Output Query
SELECT `tbl_user`.`username` AS `name`, `tbl_category`.`type` AS `Category`
FROM `tbl_user`
LEFT JOIN `tbl_category` ON tbl_category.createdby = tbl_user.useridd
LIMIT 2
use createcommand() method:
use yii\db\Query();
$connection = \Yii::$app->db;
$query = new Query;
$insql = $connection->createCommand("SELECT* FROM inventory );
$result=$insql->queryAll();
the above method list all data from the inventory table.
I post an array of skills from the form and i need to fetch list of candidates list related to the elements in array in codeigniter.
Controller
$data = array(
"mode" => $this->input->post("mode"),
"designation" => $this->input->post("designation"),
"notice_period" => $this->input->post("notice_period"),
"skill" => $this->input->post("skills"),
"cities" => $this->input->post("city")
);
$this->load->model("search_model");
$this->load->model("candidate_model");
$data["candidate"] = $this->search_model->fetch_candidate($data);
$data["designation"] = $this->candidate_model->fetch_designation();
$this->load->view('candidate_profiles', $data);
model
function fetch_candidate($data)
{
$mode = $data['mode'];
$designation = $data['designation'];
$notice_period = $data['notice_period'];
$skill = $data['skill'];
$skills = join(",",$skill);
$city = $data['cities'];
$query = $this->db->query("SELECT DISTINCT(U.user_id), U.firstname, U.lastname, U.username, U.usertype, U.email, U.phone, U.address, U.profile_image, C.name AS country,C.id AS countryid, S.name AS state,S.id AS stateid, A.housename, A.street, A.area, A.po, A.city, CJ.designation, CJ.resume, CJ.biography, CJ.hiring_mode, CJ.notice_period, CJ.current_CTC, CJ.expected_CTC, D.designation_id AS desig, D.designation AS desig_name
FROM users AS U
LEFT JOIN address AS A ON U.user_id=A.cand_id
LEFT JOIN cand_job_details AS CJ ON CJ.cand_id=U.user_id
LEFT JOIN designations AS D ON D.designation_id=CJ.designation
LEFT JOIN countries AS C ON C.id=A.country
LEFT JOIN states AS S ON S.id=A.state
LEFT JOIN user_skills AS US ON U.user_id=US.user_id
LEFT JOIN user_interested_cities AS UC ON U.user_id=UC.user_id
WHERE D.designation LIKE '$designation' && (CJ.hiring_mode='2' || CJ.hiring_mode='$mode') && CJ
.notice_period<='$notice_period' && UC.city='$city' && US.skill IN(".implode(",", $skills).")
");
return $query;
}
How to implement this on codeigniter?
Thanks in advance
You need try to add ' around each argument. After it should looks like IN ('PHP','AngularJS'), because it is a string value and datatype is varchar as well.
$skills = "'";
foreach($skill as $item) {
$skills .= $item."',";
}
$skills = trim($skills,",")
Codeigniter comes with a built in Querybuilder - i strongly suggest to use it, because it makes your life much easier, and protects you against SQL injections - which is clearly a problem in your case.
Try the following
function fetch_candidate($data)
{
$this->db
->select('SELECT DISTINCT(U.user_id), U.firstname, U.lastname, U.username, U.usertype, U.email, U.phone, U.address, U.profile_image, C.name AS country,C.id AS countryid, S.name AS state,S.id AS stateid, A.housename, A.street, A.area, A.po, A.city, CJ.designation, CJ.resume, CJ.biography, CJ.hiring_mode, CJ.notice_period, CJ.current_CTC, CJ.expected_CTC, D.designation_id AS desig, D.designation AS desig_name')
->from('users U')
->join('address A', 'U.user_id=A.cand_id', 'left')
->join('cand_job_details CJ', 'CJ.cand_id=U.user_id', 'left')
->join('designations D', 'D.designation_id=CJ.designation', 'left')
->join('countries C', 'C.id=A.country', 'left')
->join('states S', 'S.id=A.state', 'left')
->join('user_skills US', 'U.user_id=US.user_id', 'left')
->join('user_interested_cities UC', 'U.user_id=UC.user_id', 'left');
if (isset($data['designation']) && !empty($data['designation']))
{
$this->db->like('D.designation', $data['designation']);
}
if (isset($data['mode']) && !empty($data['mode']))
{
$this->db
->group_start()
->where('CJ.hiring_mode', 2)
->or_where('CJ.hiring_mode', $data['mode'])
->group_end();
}
if (isset($data['notice_period']) && !empty($data['notice_period']))
{
$this->db->where('CJ.notice_period <=', $data['notice_period']);
}
if (isset($data['city']) && !empty($data['city']))
{
$this->db->where('UC.city', $data['city']);
}
if (isset($data['skills']) && is_array($data['skills']))
{
$this->db->where_in('US.skill', $data['skills']);
}
return $this->db->get();
}
SELECT sum(`quantity`) as 'Total Product Sales',product.i_name as 'Product Name'
FROM `order_details`
inner join orders on orders.order_id = order_details.order_id and orders.status like 'C'
inner join product on product.p_id = order_details.product_id
group by order_details.product_id
You can try this Codeigniter Active Query :
Query :
public function get_data(){
$this->db->select("sum(order_details.quantity) as total_product_sales", FALSE);
$this->db->select("product.i_name as product_name'", FALSE);
$this->db->from('order_details');
$this->db->join('orders', 'orders.order_id = order_details.order_id','INNER');
$this->db->join('product', 'product.p_id = order_details.product_id', 'INNER');
$this->db->like('orders.status', 'C');
$query_result = $this->db->get();
$result = $query_result->result();
return $result;
}
I hope it will Help.
I want to join multiple tables, as in my picture:
Here is my code:
$this->db->select('
pt2.turl as `p_img`,
p.title as `p_title`,
p.text as `p_text`,
p.create as `p_date`,
pt3.turl as `c_img`,
u.name as `c_name`,
c.text as `c_text`,
c.create as `c_date`
');
$this->db->from('posts as p, users as u, photos as pt2, photos as pt3');
$this->db->join('comments as c', 'p.id=c.pid AND u.id=c.uid');
$this->db->join('posts as p2', 'p2.pid=pt2.id', 'rihgt');
$this->db->join('users as u2', 'u2.photoid=pt3.id', 'right');
$this->db->order_by('c.id', 'DESC');
$this->db->limit('7');
$qry = $this->db->get();
return $qry->result();
If I understand you correctly, this is kind of what you're looking for. I haven't tried it out so it may not be exact, but you shouldn't need to make 2 table associations (pt2 and pt3) for the same table in the join. Just Include them in the select and join on the unique ID's
The "Left" is a join that is centered around you're left table so everything hangs off of that. Since you are joining the users table before the photo table, you should be able to join on its columns.
Hope this helps. Let me know if I missed something. :)
$select = array(
pt2.turl as `p_img`,
p.title as `p_title`,
p.text as `p_text`,
p.create as `p_date`,
pt2.turl as `c_img`,
u.name as `c_name`,
c.text as `c_text`,
c.create as `c_date`
);
//Set tables to variables. Just makes it easier for me
$postsTable = "posts as p"; //This will be your left table.
$userTable = "Users as u";
$commentsTable = "comments as c";
$photosTable = "photos as pt2";
$this
->db
->select($select)
->from($postsTable)
->join($userTable, "p.uid = u.id", "left")
->join($commentsTable, "p.cid = c.id", "left")
->join($photosTable, "u.photoid = pt2.id", "left")
->get();
I solved this problem myself
It would be like this:
$select= array (
//'*',
'pt.turl p_img',
'p.title p_title',
'p.text p_text',
'p.create p_date',
'pt2.turl c_img',
'c.text c_text',
'u.name c_name',
'c.create c_date'
);
$from = array (
'posts p'
);
$qry = $this
->db
->select($select)
->from($from)
->join('comments c', 'c.pid=p.id')
->join('photos pt', 'pt.id=p.pid')
->join('users u', 'u.id=c.uid')
->join('photos pt2', 'u.photoid=pt2.id')
->order_by('c.create', 'DESC')
->limit('7')
->get();
return $qry->result();
How to do this query in Doctrine 2 QueryBuilder:
SELECT AVG(x.distance) avg_distance FROM (SELECT r.* FROM result r WHERE r.place_id = ? GROUP BY r.place_id ORDER BY r.id DESC LIMIT 100
I try this:
$dql = $qb
->select('r.*')
->from('CoreBundle:Result', 'r')
->where('r.place = :place')
->orderBy('r.id', 'DESC')
->setMaxResults(100)
->setParameter('place', $place)
->getDQL()
;
$result = $qb
->select('AVG(x.distance) avg_distance')
->from($dql, 'x')
->getQuery()
->getArrayResult();
but not work
SELECT r.* FROM': Error: Class 'SELECT' is not defined.
$sql = "SELECT AVG(x.distance) avg_distance FROM (SELECT r.* FROM result r WHERE r.place_id = :place_id ORDER BY r.id DESC LIMIT 100) x ";
$stmt = $this->em->getConnection()->prepare($sql);
$stmt->bindValue(':place_id', $place->getId());
$stmt->execute();
return $stmt->fetch();