How to have round brackets symbol in Codeigniter's active record SQL queries?
e.g. how to accomplish
SELECT * FROM `shops` WHERE (`shopid` = '10' OR `shopid` = '11') AND `shopid` <> '18'
$where="(`shopid` = '10' OR `shopid` = '11')";
$this->db->where($where, NULL, FALSE);
and for the AND condition use
$this->db->where('shopid <>', '18')
ie
$where="(`shopid` = '10' OR `shopid` = '11')";
$this->db->where($where, NULL, FALSE);
$this->db->where('shopid <>', '18')
I think you could do something like:
$where = "(`shopid` = '10' OR `shopid` = '11')";
$this->db->where($where) // or statement here
->where('shopid <>', '18') // chaining with AND
->get('shops');
Not entirely sure about the syntax, I'm writing this off the top of my head. I'll take a look at it when I get home if this doesn't work.
You can just do something like:
$this->db->select('field')->from('shops')->where("(`shopid` = '10' OR `shopid` = '11'")->where("`shopid` <> '18'");
$query = $this->db->get();
You can write your own clauses
manually:
$where = "name='Joe' AND status='boss'
OR status='active'";
$this->db->where($where);
Source: http://www.codeignitor.com/user_guide/database/active_record.html#where
$this->db->select()
->from('shops')
->where("'(`shopid` = '10' OR `shopid` = '11')")
->where('shopid !=', 18);
$this->db->get()->result();
Related
I have a query like this. How should I convert it into a eloquent or query builder
SELECT
x.MATERIAL_ID,
(SELECT TAPET_NAME FROM MA_TAPE_TYPE WHERE TAPET_CODE = x.MATERIAL_TYPE) as media_type,
(SELECT TAPEF_NAME FROM MA_TAPE_FORMAT WHERE TAPEF_CODE = x.MATERIAL_FORMAT) as media_format,
STOCK_MATERIAL_EPI.HOUSE_NO,
x.TXN_DATE,
STOCK_MATERIAL_EPI.PROGRAM_NAME,
CASE WHEN x.iden_flag = 'P' THEN STOCK_MATERIAL_EPI.epi_title WHEN x.iden_flag = 'C'
THEN STOCK_MATERIAL_EPI.prod_version_name WHEN x.iden_flag = 'M' THEN STOCK_MATERIAL_EPI.promo_name
END as episode_title,
PUR_EPISODE_HDR.EPI_NO,
(SELECT MAX (last_date) FROM run_master WHERE run_master.row_id_epi = PUR_EPISODE_HDR.row_id AND
run_master.run_aired = 'Y') as last_tx,
x.REMARKS,
x.LOCATION_ID as shelf_no,
stock_material_slag.remarks as short_list
FROM STOCK_MATERIAL x
LEFT JOIN STOCK_MATERIAL_EPI ON x.MATERIAL_ID = STOCK_MATERIAL_EPI.MATERIAL_ID
LEFT JOIN stock_material_slag ON x.MATERIAL_ID = stock_material_slag.MATERIAL_ID
LEFT JOIN PUR_EPISODE_HDR ON STOCK_MATERIAL_EPI.ROW_ID_EPI = PUR_EPISODE_HDR.ROW_ID
I'm confused as to how to convert them. Can someone help me.
I tried to write like this.
But it doesn't work,
$materials = DB::connection('oracle')
->table('STOCK_MATERIAL AS x')
->select('x.MATERIAL_ID',
DB::raw("(SELECT TAPET_NAME FROM MA_TAPE_TYPE WHERE TAPET_CODE = x.MATERIAL_TYPE) as MEDIA_TYPE"),
DB::raw("(SELECT TAPEF_NAME FROM MA_TAPE_FORMAT WHERE TAPEF_CODE = x.MATERIAL_FORMAT) as MEDIA_FORMAT"),
'x.TXN_DATE',
'y.HOUSE_NO', 'y.PROGRAM_NAME',
DB::raw("(CASE WHEN x.IDEN_FLAG = 'P' THEN z.EPI_TITLE WHEN x.IDEN_FLAG = 'C' THEN z.PROD_VERSION_NAME WHEN x.IDEN_FLAG = 'M' THEN z.PROMO_NAME END as EPISODE_TITLE)"),
'w.EPI_NO',
DB::raw("(SELECT MAX (LAST_DATE) FROM RUN_MASTER WHERE RUN_MASTER.ROW_ID_EPI = w.ROW_ID AND RUN_MASTER.RUN_AIRED = 'Y') as LAST_TX"),
'z.REMARKS',
'x.LOCATION_ID as SHELF_NO',
'z.REMARKS'
)
->leftJoin('STOCK_MATERIAL_EPI AS y', 'y.MATERIAL_ID', '=', 'x.MATERIAL_ID')
->leftJoin('STOCK_MATERIAL_SLAG AS z', 'z.MATERIAL_ID', '=', 'x.MATERIAL_ID')
->leftJoin('PUR_EPISODE_HDR AS w', 'w.ROW_ID', '=', 'y.ROW_ID_EPI')
What else do I write right?
You would need to define eloquent models and then use with(). Documentation can be found at the link below: https://laravel.com/docs/7.x/eloquent-relationships#constraining-eager-loads
example
StockMaterial::with([
'maTapeType' => function($query) {
$query->get('name')
})
])
For Query Builder you DB::raw and DB::leftJoin to create the same query.
DB::from('STOCK_MATERIAL')
->selectRaw([
'TAPET_NAME as media_type',
'CASE WHEN x.iden_flag = "P" THEN STOCK_MATERIAL_EPI.epi_title
WHEN x.iden_flag = "C" THEN STOCK_MATERIAL_EPI.prod_version_name
WHEN x.iden_flag = "M" THEN STOCK_MATERIAL_EPI.promo_name
END as episode_title',
])
->leftJoin('MA_TAPE_TYPE', 'TAPET_CODE', 'STOCK_MATERIAL.MATERIAL_TYPE')
https://laravel.com/docs/7.x/queries#raw-expressions
https://laravel.com/docs/7.x/queries#joins
I would like to replace column name with numbers in codeigniter
It does work well with letters but not with numbers
$this->db->select ('Observation.id_observation as 1');
$this->db->from ( 'Observation' );
$this->db->join ( 'Enregistrement', 'Enregistrement.id_observation =
Observation.id_observation' , 'left' );
$this->db->where('Observation.id_parcelle', $id_parcelle);
$this->db->where('Observation.id_observateur', $user_id);
$this->db->where('Observation.date_observation >=', $date_start);
$this->db->where('Observation.date_observation <=', $date_end);
return $this->db->get()->result();
Try the following
$this->db->select ('Observation.id_observation as `1`');
This will generate query as
Select `observation` as `1`....
From the Docs
Identifiers may begin with a digit but unless quoted may not consist solely of digits.
You can set alias name as string so you need to give within single quotes otherwise you will get syntax error
$this->db->select ('Observation.id_observation as `1`',FALSE);
$this->db->from ( 'Observation' );
$this->db->join ( 'Enregistrement', 'Enregistrement.id_observation =
Observation.id_observation' , 'left' );
$this->db->where('Observation.id_parcelle', $id_parcelle);
$this->db->where('Observation.id_observateur', $user_id);
$this->db->where('Observation.date_observation >=', $date_start);
$this->db->where('Observation.date_observation <=', $date_end);
return $this->db->get()->result();
OR
$var = '1';
$this->db->select ('Observation.id_observation as `'.$var.'`',FALSE);
OR
$query=$this->db->query('SELECT Observation.id_observation as "1" FROM Observation LEFT JOIN Enregistrement ON Enregistrement.id_observation =
Observation.id_observation WHERE Observation.id_parcelle = '.$id_parcelle.' AND Observation.id_observateur = '.$user_id.' AND Observation.date_observation >= "'.$date_start.'" AND Observation.date_observation <= "'.$date_end.'" ');
return $query->result();
You can try this:
$this->db->select ("Observation.id_observation as '1'");
Hope It will work.
This is what i had to do in the controller ! I very don't like this solultion but it does work:
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT
Observation.id_observation as '0',
Observation.checkseries as '1'
FROM Observation
LEFT JOIN Enregistrement ON Enregistrement.id_observation = Observation.id_observation
WHERE
Observation.id_parcelle = '$parcellecultures->id_parcelle'
AND Observation.id_observateur = '$user'
AND Observation.date_observation >= '$date_start'
AND Observation.date_observation <= '$date_end'
";
//echo $sql;
$result = $conn->query($sql);
//print_r($result);exit;
$conn->close();
I still look for another solution ....
I have a query in Query Builder in Doctrine. My query is:
$result = $this->entityManager->createQueryBuilder()
->select('cc', 'cct', 'cces')->from('App\Http\Entities\Cic\CaseCategory', 'cc')
->innerJoin('cc.type', 'cct')
->leftJoin('cc.eventSubject', 'cces')
->orderBy('cc.title')
->where('cc.active = 1')
->getQuery();
How Could I get query with AND clause? I mean to replace cc.active = 1 AND system_category=1' instead cc.active = 1 in where clause.
I'm trying in that way:
$result = $this->entityManager->createQueryBuilder()
->select('cc', 'cct', 'cces')->from('App\Http\Entities\Cic\CaseCategory', 'cc')
->innerJoin('cc.type', 'cct')
->leftJoin('cc.eventSubject', 'cces')
->orderBy('cc.title')
->where('cc.active = 1 AND system_category=1')
->getQuery();
But in that way it's dosen't work. How could I do that correctly?
I would be greateful for help.
Best regards
try this:
$result = $this->entityManager->createQueryBuilder()
->select('cc', 'cct', 'cces')->from('App\Http\Entities\Cic\CaseCategory', 'cc')
->innerJoin('cc.type', 'cct')
->leftJoin('cc.eventSubject', 'cces')
->orderBy('cc.title')
->where('cc.active = 1')
->andWhere('system_category=1')
->getQuery();
I suggest to you to use parameters like this:
$result = $this->entityManager->createQueryBuilder()
->select('cc', 'cct', 'cces')->from('App\Http\Entities\Cic\CaseCategory', 'cc')
->innerJoin('cc.type', 'cct')
->leftJoin('cc.eventSubject', 'cces')
->orderBy('cc.title')
->where('cc.active = :active')
->andWhere('system_category=:system_category')
->setParameters(
[
'active' => 1,
'system_category' => 1
]
)
->getQuery();
I have a MySQL expression that uses a conditional IF statement. As a MySQL expression, it returns TRUE or FALSE, but when I use it in CodeIgniter's query builder, I get an error. The error suggests that the outcome of the conditional is reading like a column, but how can I fix this? Thanks.
MySQL:
SELECT
positions.max_vol AS attendee_limit,
COUNT(users_positions.user_id) AS total_attendees,
IF(COUNT(users_positions.user_id) < positions.max_vol
OR positions.max_vol IS NULL,
TRUE,
FALSE) AS result
FROM
positions
INNER JOIN
users_positions ON positions.id = users_positions.position_id
WHERE
positions.id = 16
AND users_positions.calendar_date = '2016-09-05'
Function:
private function check_attendee_limit($pos_id = NULL, $date = NULL)
{
$this->db->select('positions.max_vol, COUNT(users_positions.user_id), IF(COUNT(users_positions.user_id) < positions.max_vol OR positions.max_vol IS NULL, TRUE, FALSE)');
$this->db->from('positions');
$this->db->join('users_positions', "positions.id = users_positions.position_id", 'inner');
$this->db->where('positions.id', $pos_id);
$this->db->where('users_positions.calendar_date', $date);
$query = $this->db->get();
return $query->result(); // return the rows selected
}
Error:
A Database Error Occurred
Error Number: 1054
Unknown column 'TRUE' in 'field list'
SELECT `positions`.`max_vol`, COUNT(users_positions.user_id), IF(COUNT(users_positions.user_id) < positions.max_vol OR positions.max_vol IS NULL, `TRUE`, FALSE)
FROM `positions`
INNER JOIN `users_positions` ON `positions`.`id` = `users_positions`.`position_id`
WHERE `positions`.`id` = '15'
AND `users_positions`.`calendar_date` = '2016-09-05'
Filename: models/projects/Calendar_model.php
Line Number: 141
CI adds backticks - which means you've to prevent CI from escaping your select
Try this instead
$this->db->select('positions.max_vol, COUNT(users_positions.user_id), IF(COUNT(users_positions.user_id) < positions.max_vol OR positions.max_vol IS NULL, TRUE, FALSE)', false);
If you are worry about security - in your case it doesn't matter because you don't use any user input in your select query.
You can find more informations about the Query Builder here
I am writing query like this :-
$data = array(
'company_billing' => "if (company_billing = $userId, (NULL), $userId)",
'company_admin' => "if (company_admin = $userId, (NULL), $userId)",
);
$this->db->where('id', $organizationId);
$this->db->update('organization', $data);
I was expecting something like :-
UPDATE `organization` SET `organization`.`company_billing` = if (company_billing = 2, (NULL), 2), `organization`.`company_admin` = if (company_admin = 2, (NULL), 2) WHERE `id` = 1
But I am getting :-
UPDATE `organization` SET `organization`.`company_billing` = 'if (company_billing = 2, (NULL), 2)', `organization`.`company_admin` = 'if (company_admin = 2, (NULL), 2)' WHERE `id` = 1
I want to skip those quotes around if condition block.
Is there any way to achieve this or I will have to write native query?
Thanks
::update and ::insert function values are escaped automatically producing safer queries.
$this->db->set('company_billing' , "if (company_billing = $userId, (NULL), $userId)", false);
$this->db->set('company_admin', "if (company_admin = $userId, (NULL), $userId)", false);
$this->db->where('id', $organizationId);
$this->db->update('organization');