I have $slug variable that takes frontend url slug value and sends it to model scope. Inside scope if I use echo $slug it works and also it works inside query (I have it to display products that have only same category slug).
Query where $slug works:
return $query->orwhereHas('category', function($q) use ($slug){
$q->where('slug', '=', $slug);
})->paginate($perPage, $page);
Here is the SQL:
select * from `slasher_farming_mods` where exists (select * from `slasher_farming_categories` where `slasher_farming_mods`.`category_id` = `slasher_farming_categories`.`id` and `slug` = 'medium-tractors') limit 4 offset 0
As visible slug value is "medium-tractors".
If I try to use $slug inside sort loop or inside brands loop it becomes empty
public function scopeListFrontEnd($query, $options = [], $slug = ''){
extract(array_merge([
'page' => 1,
'perPage' => 4,
'sort' => 'brandName desc',
'brands' => null,
'categorySlug' => null,
], $options));
print $slug; //This works here
if(!is_array($sort)) {
$sort = [$sort];
}
foreach ($sort as $_sort){
if(in_array($_sort, array_keys(self::$allowedSortingOptions))){
$parts = explode(' ', $_sort);
if(count($parts) < 2){
array_push($parts, 'desc');
}
list($sortField, $sortDirection) = $parts;
$query->orderBy($sortField, $sortDirection);
}
}
if($brands !== null) {
if(!is_array($brands)){
$brands = [$brands];
}
foreach ($brands as $brand){
$query->orwhereHas('brand', function($q) use ($brand){
$q->where('brand_id', '=', $brand);
});
}
}
$lastPage = $query->paginate($perPage, $page)->lastPage();
if($lastPage < $page) {
$page = 1;
}
return $query->orwhereHas('category', function($q) use ($slug){
$q->where('slug', '=', $slug);
})->paginate($perPage, $page);
}
Example SQL when using brands filter
select * from `slasher_farming_mods` where exists (select * from `slasher_farming_brands` where `slasher_farming_mods`.`brand_id` = `slasher_farming_brands`.`id` and `brand_id` = '5') or exists (select * from `slasher_farming_categories` where `slasher_farming_mods`.`category_id` = `slasher_farming_categories`.`id` and `slug` = '') order by `name` desc limit 4 offset 0
Slug variable becomes empty.
How could I keep slug variable data inside brand loop or inside sort loop?
Related
I have 3 tables guest_user_info,pg_company,user_profile.
In guest_user_info have 2 columns:
g_uid | company_id
In pg_company have 2 columns:
company_id | user_id
In user_profile have 2 columns:
id |user_email
Here i want to get user_email from user_profile.i have g_uid value (in guest_user_info table).i want company_id from guest_user_info and get the company_id and match with pg_company table,there i can get user_id.then match with that user_id with id in user_profile table.at last i need user_email from user_profile table
Well its a simple one, you just need to join using active query in CodeIgniter.
$this->db->select("UP.id", "UP.user_email");
$this->db->from("guest_user_info AS GU");
$this->db->join("pg_company AS PC", "PC.company_id=GU.company_id");
$this->db->join("user_profile AS UP", "UP.id=PC.user_id");
$this->db->where("GU.g_uid", $guid);
$query = $this->db->get();
return $query->result();
In above code, $guid you have to provide which you have.
Also please take a look at these links:
https://www.codeigniter.com/userguide3/database/query_builder.html
https://www.codeigniter.com/userguide2/database/active_record.html
You get so many things after reading this.
Check bellow code it`s working fine and common model function also
supported more then one join and also supported multiple where condition
order by ,limit.it`s EASY TO USE and REMOVE CODE REDUNDANCY.
================================================================
*Album.php
//put bellow code in your controller
=================================================================
$album_id='';//album id
//pass join table value in bellow format
$join_str[0]['table'] = 'pg_company';
$join_str[0]['join_table_id'] = 'pg_company.company_id';
$join_str[0]['from_table_id'] = 'guest_user_info.company_id';
$join_str[0]['join_type'] = '';//set join type
$join_str[1]['table'] = 'user_profile';
$join_str[1]['join_table_id'] = 'user_profile.id';
$join_str[1]['from_table_id'] = 'guest_user_info.user_id';
$join_str[1]['join_type'] = '';
$selected ="guest_user_info.*,user_profile.user_name,pg_company.name";
$condition_array=array('guest_user_info.g_uid' => $g_uid);
$albumData= $this->common->select_data_by_condition('guest_user_info', $condition _array, $selected, '', '', '', '', $join_str);
//call common model function
if (!empty($albumData)) {
print_r($albumData); // print album data
}
=========================================================================
Common.php
//put bellow code in your common model file
========================================================================
function select_data_by_condition($tablename, $condition_array = array(), $data = '*', $sortby = '', $orderby = '', $limit = '', $offset = '', $join_str = array()) {
$this->db->select($data);
//if join_str array is not empty then implement the join query
if (!empty($join_str)) {
foreach ($join_str as $join) {
if ($join['join_type'] == '') {
$this->db->join($join['table'], $join['join_table_id'] . '=' . $join['from_table_id']);
} else {
$this->db->join($join['table'], $join['join_table_id'] . '=' . $join['from_table_id'], $join['join_type']);
}
}
}
//condition array pass to where condition
$this->db->where($condition_array);
//Setting Limit for Paging
if ($limit != '' && $offset == 0) {
$this->db->limit($limit);
} else if ($limit != '' && $offset != 0) {
$this->db->limit($limit, $offset);
}
//order by query
if ($sortby != '' && $orderby != '') {
$this->db->order_by($sortby, $orderby);
}
$query = $this->db->get($tablename);
//if limit is empty then returns total count
if ($limit == '') {
$query->num_rows();
}
//if limit is not empty then return result array
return $query->result_array();
}
I build a custom query and tried use the default paginator, like this:
WodsController.php
$userId = $this->Auth->user('id');
$connection = ConnectionManager::get('default');
$result = $connection->execute("SELECT wods.id, wods.titulo , wods.dia , wods.tempo, wods.repeticoes ,userwods.user_id FROM wods
LEFT JOIN userwods ON userwods.wod_id = wods.id WHERE userwods.user_id is null or userwods.user_id=4 order by wods.dia desc limit 50")->fetchAll('assoc');
$results = array();
foreach ($result as $r) {
$entity = $this->Wods->newEntity($r);
array_push($results, $entity);
}
$wods = $this->paginate($results);
$this->set('_serialize', ['wods']);
I got this error "Unable to locate an object compatible with paginate".
Now I'm tryng implement custom query paginator, but it's not working.
I implemented paginate and paginateCount functions in the model.
Wods.php file:
public function paginate($conditions, $fields, $order, $limit, $page = 1, $recursive = null, $extra = array()) {
$recursive = -1;
$this->useTable = false;
$sql = '';
$sql .= "SELECT wods.id, wods.titulo , wods.dia , wods.tempo, wods.repeticoes ,userwods.user_id FROM wods LEFT JOIN userwods ON userwods.wod_id = wods.id WHERE userwods.user_id is null or userwods.user_id=4 order by wods.dia desc limit ";
// Adding LIMIT Clause
$sql .= (($page - 1) * $limit) . ', ' . $limit;
$results = $this->query($sql);
return $results;
}
public function paginateCount($conditions = null, $recursive = 0, $extra = array()) {
$sql = '';
$sql .= "SELECT wods.id, wods.titulo , wods.dia , wods.tempo, wods.repeticoes ,userwods.user_id FROM wods LEFT JOIN userwods ON userwods.wod_id = wods.id WHERE userwods.user_id is null or userwods.user_id=4 order by wods.dia desc";
$this->recursive = $recursive;
$results = $this->query($sql);
return count($results);
}
In the controller WodsController.php
public function index()
{
$this->Wods->recursive = 0;
$this->paginate = array('Wods'=>array('limit'=>10));
$this->set('wods', $this->paginate('Wods'));
}
But the custom paginator is not called, it continues calling the default paginate function. Why ?
Following dragmosh advise (thanks), I investigate CakePHP ORM custom queries builder.
In this solution I used find() function with specific options, after I called the default paginator:
$query = $this->Wods->find()
->select(['Wods.id', 'Wods.titulo','Wods.dia','Wods.rounds','Wods.tempo','Wods.repeticoes','Userwods.user_id'])
->join([
'table' => 'Userwods',
'alias' => 'Userwods',
'type' => 'LEFT',
'conditions' => 'Userwods.wod_id = Wods.id',
])
->where(function ($exp, $q) {
return $exp->isNull('Userwods.user_id');})
->orWhere(['Userwods.user_id' => 4])
->contain(['Userwods'])
->autoFields(true);
$wods = $this->paginate($query);
$this->set(compact('wods'));
$this->set('_serialize', ['wods']);
Am working on a student portal, below is the code i used for students position but, every user keeps getting 1st position. Every student seems to have 1st position, when they check their results from the front view. Cant seem to figure out where the problem is from in the code
function get_position($student, $class, $session, $term){
$this->db->select('*');
$this->db->from('result');
$this->db->where(array( 'class_id'=>$class, 'Session'=>$session, 'Term'=>$term));
$this->db->order_by('Total', 'asc');
$other_results = $this->db->get()->result_array();
$this->db->select("*");
$this->db->from('result');
$this->db->where(array('class_id'=> $class, 'Session'=>$session, 'Term'=>$term, 'StudentID'=>$student ));
$student_result = $this->db->get()->result_array();
$student_total = $this->get_student_total($student_result);
$position =1;
foreach($other_results as $res){
if($student_total < $res['Total']){
$position++;
}
}
return $position;
}
function get_student_total($result){
$total = 0;
foreach($result as $res){
$total+= $res['Total'];
}
return $total;
}
}
?>
I am assuming that the result table may have many records for a given studentID. Several test scores (Totals) for each student during the term right?
This should do the trick
public function get_position($student, $class, $session, $term)
{
//I like to use db method chaining.
$ranking = $this->db->select('StudentID')
->select_sum('Total', 'sumScore')
->from('result')
->where(array('class_id' => $class, 'Session' => $session, 'Term' => $term))
->group_by('StudentID')
->order_by('sumScore', 'desc')
->get()->result_array();
//The code above retrieves results from a query statement that looks like this:
//SELECT `StudentID`, SUM(`Total`) as sumScore
//FROM `result` where `class_id` = $class and `Session` = $session and `Term` = $term
//GROUP BY `StudentID`
//order by `sumScore` desc
$position = 1;
foreach($ranking as $rank)
{
if($rank['StudentID'] !== $student)
{
++$position;
}
else
{
return $position;
}
}
return NULL; //to indicate studentID was not found
}
i first checked if there any same problems like mine i ddnt find anything.
all are sorting alphanumeric column mixed with numeric data.
here is my problem.
i have a table that contain column A datas like this.
WRG-01 WRG-39 WRG-22 WRG-45 WRG-43
need to sort that as
WRG-01 WRG-22 WRG-39 WRG-43 WRG-45
this is the code i using so far in codeigniter frame work
$data['products'] = $this->db->order_by('product_id', 'asc')->get('products');
in mysql i can use this query to get done my work
preg_replace("/[^\d]/", "",'product_id'), 'asc')
How to apply it to my above codeigniter code?
here is search funtion
public function search()
{
$data['title'] = 'Search Product';
$product_name = $this->input->get('product_name');
$product_id = $this->input->get('product_id');
$product_category = $this->input->get('product_category');
$secondCategory = $this->input->get('secondCategory');
$thirdCategory = $this->input->get('thirdCategory');
$data['category'] = $this->db->order_by('id', 'asc')->get_where('categories', ['parent' => 0]);
if($product_category != '')
{
$data['secondCategory'] = $this->db->get_where('categories', ['parent' => $product_category]);
}
if($secondCategory != '')
{
$data['thirdCategory'] = $this->db->get_where('categories', ['parent' => $secondCategory]);
}
if($product_name != '')
{
$this->db->like('product_name', $product_name);
}
if($product_id != '')
{
$this->db->where('product_id', $product_id);
}
if($product_category != '')
{
$this->db->where('product_category', $product_category);
}
if($secondCategory != '')
{
$this->db->where('secondCategory', $secondCategory);
}
if($thirdCategory != '')
{
$this->db->where('thirdCategory', $thirdCategory);
}
$data['products'] = $this->db->order_by('product_id' 'asc')->get('products');
theme('all_product', $data);
}
i can't use sql query here because products is result array from product table.
Use MySQL cast
cast(product_id as SIGNED)
or
cast(product_id as UNSIGNED)
Try query like that :-
select * from products cast(product_id as UNSIGNED) ASC|DESC
Try this
$query= $this->db->query("SELECT * FROM products WHERE ??==?? ORDER BY product_id ASC");
$result= $query->result_array();
return $result;
as default data will sort by Ascending Order
This is in model. So if you pass it to controller it will return data as Objective Array.
So in controller you can access
$result = $this->model_name->method_for_above_code();
$name = $result[0]['name'];
$id = $result[0]['id'];
if in View
$result['this_for_view'] = $this->model_name->method_for_above_code();
foreach ($this_for_view as $new_item) {
echo "Name is ".$new_item['name'];
echo "ID is ".$new_item['id'];
}
I'm using codeigniter framework to develop one music cms. i have 3 tables in mysql database, Currently im working in "Album" Table and "Model, Controller". i want to SELECT "Album" Table 1 and JOIN "Album" -> "cat_id" with "Category" -> "cat_id", and fetch all categories records.
Then i want to JOIN "Album" -> "album_id" on "Soundtrack" -> "album_id" then fetch all soundtrack records A to Z.
Please somebody help me to show proper codeigniter query, how i can SELECT and JOIN Tables then fetch records from 3 tables, ?
Table 1 -> Category
cat_id
cat_name
cat_title
date
Table 2 -> Album
cat_id
album_id
album_title
album_details
Table 3 -> Soundtrack
album_id
track_title
track_url
date
Use this code in model
public function funcname($id)
{
$this->db->select('*');
$this->db->from('Album a');
$this->db->join('Category b', 'b.cat_id=a.cat_id', 'left');
$this->db->join('Soundtrack c', 'c.album_id=a.album_id', 'left');
$this->db->where('c.album_id',$id);
$this->db->order_by('c.track_title','asc');
$query = $this->db->get();
if($query->num_rows() != 0)
{
return $query->result_array();
}
else
{
return false;
}
}
try this
In your model
If u want get all album data use
function get_all_album_data() {
$this->db->select ( '*' );
$this->db->from ( 'Album' );
$this->db->join ( 'Category', 'Category.cat_id = Album.cat_id' , 'left' );
$this->db->join ( 'Soundtrack', 'Soundtrack.album_id = Album.album_id' , 'left' );
$query = $this->db->get ();
return $query->result ();
}
if u want to get specific album data use
function get_album_data($album_id) {
$this->db->select ( '*' );
$this->db->from ( 'Album' );
$this->db->join ( 'Category', 'Category.cat_id = Album.cat_id' , 'left' );
$this->db->join ( 'Soundtrack', 'Soundtrack.album_id = Album.album_id' , 'left' );
$this->db->where ( 'Album.album_id', $album_id);
$query = $this->db->get ();
return $query->result ();
}
Try this one for data...
function get_album_data() {
$this->db->select ( 'album.*,cat.*,s_track.*' )
->from ( 'albums as album' )
->join ( 'categories cat', 'cat.cat_id = album.cat_id')
->join ( 'soundtracks s_tracks ', 's_tracks.album_id = album.album_id');
$query = $this->db->get ();
return $query->result ();
}
while for datum try this...
function get_album_datum($album_id) {
$this->db->select ( 'album.*,cat.*,s_track.*' )
->from ( 'albums as album' )
->join ( 'categories cat', 'cat.cat_id = album.cat_id')
->join ( 'soundtracks s_tracks ', 's_tracks.album_id = album.album_id');
$this->db->where ( 'album.album_id', $album_id);
$query = $this->db->get ();
return $query->row();
}7
855788
Check bellow code it`s working fine and common model function also
supported more then one join and also supported multiple where condition
order by ,limit.it`s EASY TO USE and REMOVE CODE REDUNDANCY.
================================================================
*Album.php
//put bellow code in your controller
=================================================================
$album_id='';//album id
//pass join table value in bellow format
$join_str[0]['table'] = 'Category';
$join_str[0]['join_table_id'] = 'Category.cat_id';
$join_str[0]['from_table_id'] = 'Album.cat_id';
$join_str[0]['join_type'] = 'left';
$join_str[1]['table'] = 'Soundtrack';
$join_str[1]['join_table_id'] = 'Soundtrack.album_id';
$join_str[1]['from_table_id'] = 'Album.album_id';
$join_str[1]['join_type'] = 'left';
$selected = "Album.*,Category.cat_name,Category.cat_title,Soundtrack.track_title,Soundtrack.track_url";
$albumData= $this->common->select_data_by_condition('Album', array('Soundtrack.album_id' => $album_id), $selected, '', '', '', '', $join_str);
//call common model function
if (!empty($albumData)) {
print_r($albumData); // print album data
}
=========================================================================
Common.php
//put bellow code in your common model file
========================================================================
function select_data_by_condition($tablename, $condition_array = array(), $data = '*', $sortby = '', $orderby = '', $limit = '', $offset = '', $join_str = array()) {
$this->db->select($data);
//if join_str array is not empty then implement the join query
if (!empty($join_str)) {
foreach ($join_str as $join) {
if ($join['join_type'] == '') {
$this->db->join($join['table'], $join['join_table_id'] . '=' . $join['from_table_id']);
} else {
$this->db->join($join['table'], $join['join_table_id'] . '=' . $join['from_table_id'], $join['join_type']);
}
}
}
//condition array pass to where condition
$this->db->where($condition_array);
//Setting Limit for Paging
if ($limit != '' && $offset == 0) {
$this->db->limit($limit);
} else if ($limit != '' && $offset != 0) {
$this->db->limit($limit, $offset);
}
//order by query
if ($sortby != '' && $orderby != '') {
$this->db->order_by($sortby, $orderby);
}
$query = $this->db->get($tablename);
//if limit is empty then returns total count
if ($limit == '') {
$query->num_rows();
}
//if limit is not empty then return result array
return $query->result_array();
}
Try as follows:
public function funcname($id)
{
$this->db->select('*');
$this->db->from('Album a');
$this->db->join('Category b', 'b.cat_id=a.cat_id', 'left');
$this->db->join('Soundtrack c', 'c.album_id=a.album_id', 'left');
$this->db->where('c.album_id',$id);
$this->db->order_by('c.track_title','asc');
$query = $this->db->get();
return $query->result_array();
}
If no result found CI returns false otherwise true
public function getdata(){
$this->db->select('c.country_name as country, s.state_name as state, ct.city_name as city, t.id as id');
$this->db->from('tblmaster t');
$this->db->join('country c', 't.country=c.country_id');
$this->db->join('state s', 't.state=s.state_id');
$this->db->join('city ct', 't.city=ct.city_id');
$this->db->order_by('t.id','desc');
$query = $this->db->get();
return $query->result();
}