How to get to join table Codeigniter - php

My model:
public function category($column, $value)
{
$this->db->select('c.cat2, c.category, m.id, m.date, m.when_date, m.when_time, m.where_m, m.age1, m.age2, m.opis, m.rozpoznamy');
$this->db->from('category c');
$this->db->where($column, $value);
$this->db->join('meeting m', 'm.id_cat = c.id');
$result = $this->db->get();
return $result->result();
}
public function delete($where, $column, $value)
{
$this->db->delete($this->users_m->category($column, $value), $where);
}
My controler:
public function delete()
{
$cat = $this->uri->segment(3);
$value = $this->uri->segment(4);
$column = 'm.id';
$where = array('m.id' => $value);
$this->users_m->delete($where, $column, $value);
redirect('main/category/' . $cat);
}
I have problem to delete data from join table, get this message when I try delete:
A Database Error Occurred
Error Number: 1146
Table 'ci.object' doesn't exist
DELETE FROM `Object` WHERE `m`.`id` = '13'
Filename: C:\xampp\htdocs\ci\system\database\DB_driver.php
Line Number: 330
So probably theres a problem with table in function delete. I try on different ways to get to this table and I don't know how to solve this. Any clue?

You're passing a CI Object into $this->db->delete() as $this->users_m->category() returns a DB result array of object(s).
CI Delete works by passing in the table name, in your case it looks like it will be
public function delete($where) {
$this->db->where('meeting m', $where);
$this->db->delete('meeting');
}
I can't work out why you have extra values in there

Related

How count a column from a tableB where tableA.y = TableB.y laravel

I would like to count number of courses and questions of each modules.
When I try it with this code below, it displays the counting of all questions
//$data = DB::table('module')->orderBy('idmodule', 'desc')->paginate(5);
$data = DB::table('module')
->leftJoin('cours', 'module.idmodule', '=', 'cours.id_module')
->leftJoin('question', 'cours.id_cours', '=', 'question.id_cours')
->select('module.*', 'cours.*',DB::raw("count(cours.id_module) as cours"),DB::raw("count(question.id_cours) as quest"))
->groupBy('module.idmodule')
->get();
$id = Auth::id();
return view('admin.modules',compact('data'))>with('profile',profile::find($id));
If you declare the relation between Module->Cour and Module->Question, you can simply do
$modules = Modules::withCount(['cours', 'questions'])->get();
Module.php :
public function cours()
{
return $this->hasMany(Cour::class, 'id_module', 'idmodule');
}
public function questions()
{
return $this->hasManyThrough(Question::class, Cour::class, 'id_module', 'id_cours', 'idmodule', 'id_cours');
}

Call to undefined method CI_DB_mysql_driver::row_array()

Hey i am novice in CI so please forgive! I am trying to join 2 tables in codeigniter and i am getting here these error in my code
Call to undefined method CI_DB_mysql_driver::row_array() in
C:\xampp\htdocs\Hostel\application\models\payfees.php on line 16.
My Code for the method is here like these
public function payu($id,$month){
$where = "where generatebills.student_id='".$id."' and generatebills.month='".$month."'";
$query = $this->db->select('*')
->from('generatebills')
->join('student','student.student_id=generatebills.student_id')
->where($where);
return $query->row_array();
}
Don't forget the missing ->get() method. Plus, remove the WHERE in the string:
$where = "name='Joe' AND status='boss' OR status='active'";
http://www.codeigniter.com/userguide2/database/active_record.html
I'd suggest use an array instead:
public function payu($id,$month)
{
// $where = "generatebills.student_id='".$id."' and generatebills.month='".$month."'";
$where = array(
'generatebills.student_id' => $id,
'generatebills.month' => $month,
);
$query = $this->db->select('generatebills.*')
->from('generatebills')
->join('student','student.student_id = generatebills.student_id')
->where($where);
return $query->get()->row_array();
// ^
}

I need to call a controller function inside a view -Codeigniter

I need to call a function from view to echo a value. I use following code,
Controller (test_controller)
public function displayCategory()
{
$this->load->model('Model_test');
$data['categories'] = $this->Model_test->getCategories();
$this->load->view('test_view', $data);
}
public function display($id)
{
$this->load->model('Model_test');
$name= $this->Model_test->getName($id);
return $name;
}
Model (Model_test)
function getCategories() {
$query = $this->db->query("SELECT * FROM category");
if ($query->num_rows() > 0) {
return $query->result();
} else {
return NULL;
}
}
function getName($userId) {
$query = $this->db->query("SELECT name FROM user where id = '$userId' ");
if ($query->num_rows() > 0) {
return $query->row()->name;
} else {
return NULL;
}
}
View
<div id="body">
<?php
foreach ($categories as $object) {
$temp = $this->test_controller->display($object->id);
echo $object->title . " ". $object->no . $temp . '<br/>';
}
?>
</div>
but some error when running the code.
error Message: Undefined property: CI_Loader::$test_controller in view
I am not sure if you use CodeIgniter 2 or 3.
Anyway, basically you don't want to use anything inside View files except perhaps helper function(s) or some kind of "presenter" layer (that should be called inside controller I guess).
Solution using Join
Go and read this manual page and search for join. There you can learn about implementation of SQL join directive.
You want to modify this (getCategories()) function so it returns data that you require
function getCategories() {
$this->db->select('category.title, category.no, user.name as username')
->from('category')
->join('user', 'user.id = category.id');
$query = $this->db->get();
if ($query->num_rows() > 0) {
return $query->result();
} else {
return NULL;
}
}
and in view you can get your username like this
foreach ($categories as $object) {
echo $object->title . " ". $object->no . $object->username . '<br/>';
}
I am not 100% sure so please post comments I will edit this answer later.
Solution "breaking rules"
https://stackoverflow.com/a/24320884/1564365
general notes
Also consider naming your tables using plural so categories, users...
Also it is a bad practise to use "category.id as user.id" (storing user id inside category table in "id" field) instead you shold use either a pivot table or in case of 1:1 relation field "user_id".

laravel advanced search

I want to make an advanced search in which the user has optional parameters to search,am joining data from three tables as follows
$qry="SELECT rooms.*, salereservation.*, customers.*
FROM rooms
JOIN salereservation
ON salereservation.room_id = rooms.room_id
JOIN customers
ON customers.id = salereservation.customer_id
WHERE salereservation.sale_status=1 AND ";
i am appending to the query string the optional parameters as follows
if($fname!=''){
$qry.="fname LIKE %fname% AND ";
}
if($lname!=''){
$qry.="lname LIKE %:lname% AND ";
}
if($time_in!=''){
$qry.="start_datetime LIKE %time_in% AND ";
}
if($time_out!=''){
$qry.="end_datetime LIKE %time_out% AND ";
}
if($phone!=''){
$qry.="phone LIKE %phone% AND ";
}
if($room_no!=''){
$qry.="room_no LIKE %room_no%";
}
my problem is how to turn the code into laravel query builder
I didn't try this code but its should work under laravel 4.2.
$query = DB::table('rooms')
->join("salereservation", "salereservation.room_id", "=", "rooms.room_id")
->join("customers", "customers.id", "=", "salereservation.customer_id")
->where("salereservation.sale_status",'=',1)
->select('rooms.*', 'salereservation.*', 'customers.*');
if($fname!=''){
$query->where("fname",'like',"%$fname%");
}
if($lname!=''){
$query->where("lname",'like',"%$lname%");
}
if($time_in!=''){
$query->where("start_datetime",'like',"%$time_in%");
}
if($time_out!=''){
$query->where("end_datetime",'like',"%$time_out%");
}
if($phone!=''){
$query->where("phone",'like',"%$phone%");
}
if($room_no!=''){
$query->where("room_no",'like',"%$room_no%");
}
$data = $query->get(); //finally get the result
Update:
For query verification you can print your query using:
$queries = DB::getQueryLog();
$last_query = end($queries);
dd($last_query);
And verify if your query different from your desired query.
If something went to different we can upgrade our query structure according to them.and also can you update with your latest query generated from laravel methods.
But if you still face some difficulties to understand my point of view. let me know.
You have to setup your DB like this:
rooms:
- id
- room_no
reservations:
- customer_id
- start_datetime
- end_datatime
- room_id
customers:
- lname
- fname
- phone
Then setup the propers relationships in your models
//Reservation model
class Reservation extends \Eloquent {
public function room()
{
return $this->belongsTo('Room', 'room_id');
}
public function customer()
{
return $this->belongsTo('Customer', 'customer_id');
}
}
Create a query scope like the following :
// Reservation model
// $terms is an array which pairs column_name to the querying value
public function scopeSearch($query, $terms)
{
if ( ! empty($terms['room_no']))
{
$query->has('rooms.room_no', $terms['room_no']);
}
$customer_cols = ['lname', 'fname', 'phone'];
$reservations_cols = ['start_datetime', 'end_datetime'];
foreach ($terms as $key => $value)
{
if (in_array($key, $customer_cols))
{
$query->whereHas('customer', function($subquery) use ($key, $value)
{
$subquery->where($key, 'like', '%'.$value.'%');
});
}
if (in_array($key, $reservation_cols))
{
$query->where($key, $value);
}
}
}
Now you can invoke your query scope by doing the following:
$reservations = Reservation:search(array('fname' => 'value', 'lname' => 'value2', ...));
And accessing results by:
foreach ($reservations as $res)
{
$res->room->number;
$res->customer->name;
}

is it possible to join a single table it self?

this is the model function i am trying join the single database table it self the , parent::get method fetch the data from the table !
public function get_with_parents($id=NULL,$single=FALSE){
$this->db->select('pages.*','p.slug as parent_slug','p.title as parent_title');
$this->db->join('pages as p','pages.parent_id=p.id','left');
return parent::get($id,$single);
}
this is the controller!!
$this->data ['pages'] = $this->Page_model->get_with_parents();
Assuming your single tables is called pages, this should work -
$this->db->select('p1.title as ptitle','p.slug as parent_slug','p.title as parent_title');
$this->db->from('pages AS p1');
$this->db->join('pages AS p','p1.parent_id=p.id','left');
public function get_with_parent($id = NULL,$sengle = FALSE)
{
$this->db->select('pages.*,p.slug as parent_slug,p.title as parent_title')
->where("pages.language", $this->uri->segment(1))
->join('pages as p','pages.parent_id=p.id','left');
return parent::get($id,$sengle);
}
or
public function get_with_parent ()
{
$this->db->select('pages.*, p.slug as parent_slug, p.title as parent_title')
->where("pages.language", $this->uri->segment(1))
->join('pages as p', 'pages.parent_id=p.id', 'left');
$query = $this->db->get('pages');
return $query->result();
}

Categories