I have a JOIN query in CodeIgniter which returns an empty array.
My Controller part:
if ($this->session->has_userdata('user')) {
$id = $this->session->user['id'];
$where = ["products.user_id =" => $id];
$status = $this->insertModel->get_status($where);
$this->load->view('profile', ["status" => $status]);
}
My model:
return $this->db
->from('photos')
->join('products', 'photos.prod_id = products.id', 'left')
->where($where)
->get()
->result_array();
in your controller, just send $id instead of $where
$status = $this->insertModel->get_status($id);
and rebuild your where clause in your model the Codeigniter way:
->where('products.user_id', $id)
see the docs here
and about MVC (Model=database interaction, View=browser output and Controller=your application logic)
Controller:
Your error is in $where, check my code
if ($this->session->has_userdata('user')) {
$id = $this->session->user['id'];
//$where = ["products.user_id =" => $id];//old line
$where = array("products.user_id" => $id);//new line
$status = $this->insertModel->get_status($where);
$this->load->view('profile', ["status" => $status]);
}
Related
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);
}
i have searching routes with get and post. First time users select search filters from home page then it submit it hit on index controller search with form data and return correct results with pagination when i click on pages it does not show any thing.
Route::post('search', 'SearchController#index');
Route::get('search', 'SearchController#index');
And i have index controller for search with post first time and with session like this.
public function index(Request $request)
{
if( Request::get('select_menu') !='' ){
$conditions = array();
$conditions['city'] = Request::get('city');
$conditions['area'] = Request::get('area');
$conditions['purpose'] = Request::get('status');
$results = Property::where($conditions)->whereBetween('price', array(1000, 10000))->paginate(6);
Session::set('formDataSession', $conditions);
}
elseif(Session::has('formDataSession')){
$getSession = Session::get('formDataSession');
$conditions = array();
$conditions['city'] = $getSession['city'];
$conditions['area'] = $getSession['area'];
$conditions['purpose'] = $getSession['purpose'];
$results = Property::where($conditions)->whereBetween('price', array(1000, 10000))->paginate(6);
}
return view('search', array('page' => 'search','results'=>$results));
}
public function index(Request $request)
{
$results = Property::whereBetween('price', [1000, 10000]);
$conditions = [];
if ($request->has('select_menu')) {
$conditions['city'] = $request->city;
$conditions['area'] = $request->area;
$conditions['purpose'] = $request->status;
session(['formDataSession' => $conditions]);
}
$getSession = session('formDataSession');
$conditions['city'] = $getSession['city'];
$conditions['area'] = $getSession['area'];
$conditions['purpose'] = $getSession['purpose'];
$results = $results->where($conditions)->paginate(6);
return view('search', ['page' => 'search', 'results' => $results]);
}
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']);
I'm having a problem while running this code:
//DashboardController
public function getStream()
{
$user = Sentry::getUser();
$userid = $user->id;
$convs = TBMsg::getUserConversations($userid);
$getNumOfParticipants = $convs->getNumOfParticipants();
$participants = $convs->getAllParticipants();
$lastMessage = $convs->getLastMessage();
$senderId = $lastMessage->getSender();
$content = $lastMessage->getContent();
$status = $lastMessage->getStatus();
$posts = Post::whereIn('user_id', function($query) {
$query->select('follow_id')
->from('user_follows')
->where('user_id', '1');
})->orWhere('user_id', '1')->get();
return View::make('stream', array('getNumOfParticipants' => $getNumOfParticipants,
'participants' => $participants,
'lastMessage' => $lastMessage,
'senderId' => $senderId,
'content' => $content,
'status' => $status
))->with('posts', $posts)->with('convs', $convs);
}
}
I got this error: Call to undefined method Illuminate\Support\Collection::getNumOfParticipants()
http://i.stack.imgur.com/9N3xU.png
Replace ->get() with ->first() as right now you're basically returning an collection of arrays but you need that.
$query->select('follow_id')
->from('user_follows')
->where('user_id', '1');
})->orWhere('user_id', '1') // ->get() is removed
->first();
$convs is a collection so you can't call a method on it that only exists on a single model. Like the tutorial of the package suggests you have to iterate over the collection to use that function.
From the how to:
foreach ( $convs as $conv ) {
$getNumOfParticipants = $conv->getNumOfParticipants();
$participants = $conv->getAllParticipants();
/* $lastMessage Tzookb\TBMsg\Entities\Message */
$lastMessage = $conv->getLastMessage();
$senderId = $lastMessage->getSender();
$content = $lastMessage->getContent();
$status = $lastMessage->getStatus();
}
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();