GROUP a result of JOINS using QUERY BUILDER in Codeigniter - php

I have the following function, the params are "asc,PV1"
public function get_products($order, $sku){
if(is_array($result) && $result['active']){
$id_emp = $result['id_emp'];
$mts = 'module_tienda_status';
$mtc = 'module_tienda_categories';
$mtp = 'module_tienda_productos';
$mtpt = 'module_tienda_product_type';
$mtpa = 'module_tienda_product_attribute';
$mta = 'module_tienda_attributes';
$mtao = 'module_tienda_attribute_option';
$mtpv = 'module_tienda_product_variation';
$mtpvo = 'module_tienda_product_variation_options';
$get = array(
$mtp.'.id',
$mtp.'.name',
$mtp.'.sku',
$mtp.'.desc_short',
$mtp.'.desc_long',
$mtp.'.id_category',
$mtp.'.price',
$mtp.'.id_status',
$mtp.'.inventory',
$mtp.'.imgs',
$mtp.'.qty',
$mtp.'.featured',
$mtc.'.name as cat_name',
$mtpt.'.id as type_id',
$mtpa.'.id_attribute',
$mtpa.'.id_option',
$mta.'.name as attr_name',
$mtao.'.option as opt_name',
$mtpv.'.inventory as var_inv',
$mtpv.'.qty as var_qty',
$mtpv.'.price as var_price',
$mtpvo.'.id_product_variation as var_id',
$mtpvo.'.id_attribute as var_attr',
$mtpvo.'.id_option as var_opt'
);
$this->db->select($get);
$this->db->from($mts);
$this->db->join($mtp, $mtp.'.id_status = '.$mts.'.id');
$this->db->join($mtc, $mtp.'.id_category = '.$mtc.'.id', 'left');
$this->db->join($mtpt, $mtp.'.id_product_type = '.$mtpt.'.id');
$this->db->join($mtpa, $mtpa.'.id_product = '.$mtp.'.id', 'left');
$this->db->join($mta, $mta.'.id = '.$mtpa.'.id_attribute', 'left');
$this->db->join($mtao, $mtao.'.id = '.$mtpa.'.id_option', 'left');
$this->db->join($mtpv, $mtp.'.id = '.$mtpv.'.id_product', 'left');
$this->db->join($mtpvo, $mtpv.'.id = '.$mtpvo.'.id_product_variation', 'left');
$this->db->where($mtp.'.id_emp', $id_emp);
if($sku != 'null'){
$this->db->where($mtp.'.sku', $sku);
}
if(!is_null($order)){
$this->db->order_by('module_tienda_productos.created', $order);
}
$query = $this->db->get()->result();
}else{
return $result;
}
}
the result is an array with 49 rows of the same product, the difference is that there are different attributes and variations, here is the example https://pastebin.com/3X4w6wEi
What i want is 1 single result with an array of attributes and 1 array of variations something like this (is a json, please decode it)
[{'id':'343','name':'Producto variable 1','sku':'PV1','desc_short':'<p><br></p>','desc_long':'<p><br></p>','id_category':null,'price':null,'id_status':'1','inventory':'0','imgs':null,'qty':'0','featured':'0','cat_name':null,'type_id':'2','attributes':[{'id_attribute':'49','attr_name':'Colors','opts':{'107':'Amarillo','110':'Celeste','121':'Rojo','122':'Azul'}},{'id_attribute':'57','attr_name':'Size','opts':{'112':'xs','113':'s','114':'n','116':'xl'}}],'variations':[{'var_id':'42','var_inv':'0','var_qty':'0','var_price':'0.00','opts':[{'id_attribute':'49','attr_name':'Colors','opts':{'107':'Amarillo','110':'Celeste','121':'Rojo','122':'Azul'}},{'id_attribute':'57','attr_name':'Size','opts':{'112':'xs'}}]}]}]

Related

Codeigniter display TYPE_LABLE from TYPE table if result equal to specific CATEGORY

I'm working on Codeigniter rest API project and came across a problem. I would like my model to select additional data by condition.
if CATEGORY equals $CATEGORY show TYPE.TYPE_LABLE
otherwise just don't show "TYPE.TYPE_LABLE"
so how can i get this result?
thank you for your help.
function get_data() {
$id = isset($_REQUEST['id']) ? $_REQUEST['id'] : '';
$CATEGORY = array('CATEGORY1', 'CATEGORY2', 'CATEGORY3', 'CATEGORY4');
$types = array('type_1', 'type_2');
if ($id != null) {
$this->db->where('ID',$id);
//selct TYPE.TYPE_LABLE if CATEGORY equals $CATEGORY
$this->db->select('POST.ID, POST.DATE, TYPE.Post_Type as P_TYPE, TYPE.TYPE_LABLE$CATEGORY', FALSE);
$this->db->join('TYPE', 'POST.TYPE_ID = TYPE.ID', 'left');
$this->db->join('CATEGORY', 'POST.CATEGORY_ID = CATEGORY.ID', 'left');
$this->db->order_by('POST.ID', 'DESC');
$this->db->where_in('POST.Post_Type', $types);
$this->db->where('POST.DATE >', date('Y-m-d', strtotime('01-01-2019')) );
$this->db->from('POST');
$result = $this->db->get();
}
return $result;
}

Codeigniter Search with Where Condition Issue

I am new in PHP and learning Codeigniter. I have an issue to put where condition with my search query. My controller is like below
public function index(){
$data = array();
// Get messages from the session
if($this->session->userdata('success_msg')){
$data['success_msg'] = $this->session->userdata('success_msg');
$this->session->unset_userdata('success_msg');
}
if($this->session->userdata('error_msg')){
$data['error_msg'] = $this->session->userdata('error_msg');
$this->session->unset_userdata('error_msg');
}
// If search request submitted
if($this->input->post('submitSearch')){
$inputKeywords = $this->input->post('searchKeyword');
$searchKeyword = strip_tags($inputKeywords);
if(!empty($searchKeyword)){
$this->session->set_userdata('searchKeyword',$searchKeyword);
}else{
$this->session->unset_userdata('searchKeyword');
}
}elseif($this->input->post('submitSearchReset')){
$this->session->unset_userdata('searchKeyword');
}
$data['searchKeyword'] = $this->session->userdata('searchKeyword');
// Get rows count
$conditions['searchKeyword'] = $data['searchKeyword'];
$conditions['returnType'] = 'count';
$rowsCount = $this->member->getRows($conditions);
// Pagination config
$config['base_url'] = base_url().'members/index/';
$config['uri_segment'] = 3;
$config['total_rows'] = $rowsCount;
$config['per_page'] = $this->perPage;
// Initialize pagination library
$this->pagination->initialize($config);
// Define offset
$page = $this->uri->segment(3);
$offset = !$page?0:$page;
// Get rows
$conditions['returnType'] = '';
$conditions['start'] = $offset;
$conditions['limit'] = $this->perPage;
$data['members'] = $this->member->getRows($conditions);
$data['title'] = 'Members List';
// Load the list page view
//$this->load->view('templates/header', $data);
$this->load->view('members/index', $data);
//$this->load->view('templates/footer');
}
and my model is like below
function getRows($params = array()){
$this->db->select('*');
$this->db->from($this->table);
//$where = "is_verified = 1";
//$this->db->where($where);
if(array_key_exists("conditions", $params)){
foreach($params['conditions'] as $key => $val){
$this->db->where($key, $val);
}
}
if(!empty($params['searchKeyword'])){
$search = $params['searchKeyword'];
$likeArr = array('fname' => $search, 'lname' => $search, 'gran_id' => $search);
$this->db->or_like($likeArr);
}
if(array_key_exists("returnType",$params) && $params['returnType'] == 'count'){
$result = $this->db->count_all_results();
}else{
if(array_key_exists("user_id", $params)){
$this->db->where('user_id', $params['user_id']);
$query = $this->db->get();
$result = $query->row_array();
}else{
$this->db->order_by('fname', 'asc');
if(array_key_exists("start",$params) && array_key_exists("limit",$params)){
$this->db->limit($params['limit'],$params['start']);
}elseif(!array_key_exists("start",$params) && array_key_exists("limit",$params)){
$this->db->limit($params['limit']);
}
//$query = $this->db->get();
$query = $this->db->where('is_verified', '1')->get();
$result = ($query->num_rows() > 0)?$query->result_array():FALSE;
}
}
// Return fetched data
return $result;
}
I want to fetch only records where
is_verified = 1
and so I have put it with my query and its working fine without search query. If I search its showing record even if_verified have another value. I am not getting idea which another place I should put this where condition so when I search, it can show only required records.
Thanks!
This will happen when using or_like in Codeigniter you should use group_start and group_end function to separate your search with where condition
if(!empty($params['searchKeyword'])){
$search = $params['searchKeyword'];
$likeArr = array('fname' => $search, 'lname' => $search, 'gran_id' => $search);
$this->db->group_start(); // this will make brackets for your search query
$this->db->or_like($likeArr);
$this->db->group_end();
}
You are not filtering the query when a search is performed you're only doing it outside of a search.
Try: Find this block
if(!empty($params['searchKeyword'])){
$search = $params['searchKeyword'];
$likeArr = array('fname' => $search,'lname' => $search, 'gran_id' => $search);
$query = $this->db->where('is_verified', '1');
$this->db->or_like($likeArr);
}

How to correctly alias a table in codeigniter?

I would like to do a join between 2 tables from my db.
this is my code:
public function getEpisodes($limit = 12, $order = 'id_e', $das = 'desc')
{
$this->db->select('e.id_e, e.id_s, e.num_e, s.id_s, s.nom_s, s.thumb_s')
->from('s_episodes as e, s_series as s')
->join('s', 'e.id_s = s.id_s', 'left')
->order_by('e.'.$order, $das)
->limit($limit);
$query = $this->db->get();
return $query->result_array();
}
This is the error code I get, when running my code:
What is wrong with my table alias?
Maybe try moving the s_series as s...
public function getEpisodes($limit = 12, $order = 'id_e', $das = 'desc')
{
$this->db->select('e.id_e, e.id_s, e.num_e, s.id_s, s.nom_s, s.thumb_s')
// Move s_series as s
->from('s_episodes as e')
->join('s_series as s', 'e.id_s = s.id_s', 'left')
->order_by('e.'.$order, $das)
->limit($limit);
$query = $this->db->get();
return $query->result_array();
}

How to apply filter in codeigniter in 'where' condition using 'if' condition?

I am trying to apply a filter using codeigniter, but it's not working. It works for a single array record, but when I send multiple comma-separated source parameters it doesn't filter.
Here is my code in model.
$user_id = $this->input->post('user_id');
$source = $this->input->post('source');
$source = explode(',', $source);
$radius = $this->input->post('radius');
$this->db->select('post.*, source.*, user.firstname, user.lastname');
$this->db->from('post');
$this->db->join('user', 'user.id = post.cop_id');
$this->db->join('source', 'post.source_id = source.id');
$this->db->where('post.cop_id', $user_id);
if (in_array("1", $source)) {
$this->db->where('post.source_id', 1);
}
if (in_array("2", $source)) {
$this->db->where('post.source_id', 2);
}
if (in_array("3", $source)) {
$this->db->where('post.source_id', 3);
}
if (in_array("4", $source)) {
$this->db->where('post.source_id',4);
}
if (!empty($radius)) {
$this->db->where('post.post_radius', $radius);
}
$this->db->where('post.source_id !=', 4);
$query = $this->db->get();
return $query->result();
Use where_in
$this->db->select('post.*, source.*, user.firstname, user.lastname');
$this->db->from('post');
$this->db->join('user', 'user.id = post.cop_id');
$this->db->join('source', 'post.source_id = source.id');
$this->db->where('post.cop_id', $user_id);
$this->db->where_in('post.source_id', $source);// it will produse IN ('1', '2', '3')
$this->db->where('post.post_radius', $radius);

Is it possible to split query builder in Laravel?

Is it possible to split queries somehow like this?
public function getStatuses($dates)
{
$query = DB::table('tickets');
if ($dates['from'])
$query = $query->where('from', $dates['from']);
if ($dates['to'])
$query = $query->where('to', $dates['to']);
$query = $query->select('Active');
return $query->get()->toArray();
}
Yes, it's possibile. But don't reassign to the same variable or you risk messing it up:
public function getStatuses($dates)
{
$query = DB::table('tickets');
if ($dates['from'])
$query->where('from', $dates['from']);
if ($dates['to'])
$query->where('to', $dates['to']);
$query->select('Active');
return $query->get()->toArray();
}
In Laravel 4, its necessary to assign the get method to a variable
public function scopeGetPosts($query, $this_user = NULL){
$results = DB::table('post')
->select('*')
->where('post_status','=','publish');
if( $this_user != NULL ){
$results->where('post_author','=',$this_user->user_id);
}
$data = $results->orderBy('created_at', 'desc')
->get();
if( empty( $results ) )
$data = 'no results';
return $data;
}
In Laravel Eloquent :
$query = ModelName::where('status',1);
if($userId){
$query->where('user_id',$userId);
}
if($limit){
$query->limit($limit);
}
$result = $query->get();

Categories