is it possible to join a single table it self? - php

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();
}

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');
}

How to join these tables in codeigniter

I am facing problem to join these tables and also know how to make controller code to view data in view file with text boxes.
public function get_order_return_info()
{
$this->db->select('tbl_order_details.*', false);
$this->db->select('tbl_order_details.order_details_id', false);
$this->db->select('tbl_order.order_id', false);
$this->db->select('tbl_product.product_id', false);
$this->db->select('tbl_inventory.product_quantity', false);
$this->db->from('tbl_order_details');
$this->db->join('tbl_order', 'tbl_order_details.order_id = tbl_order.order_id ', 'left');
$this->db->join('tbl_product', 'tbl_order_details.product_code = tbl_product.product_id ', 'left');
$this->db->join('tbl_inventory', 'tbl_product.product_id = tbl_inventory.product_id ', 'left');
$query_result = $this->db->get();
$result = $query_result->result();
return $result;
}
You can use MVC to solve this
//Controller
function get_data() {
$data['list'] = $this->your_model->get_data();
$this->load->view('your_view/location',$data);
}
//Model
function get_data() {
$sql = "your_query";
$list = $this->db->query($sql)->result_array();
return $list;
}
//View
foreach($list as $data) {
echo $data['your_selected_field']; // it could be table,text field,or just text
}
API Reference : https://www.codeigniter.com/user_guide/database/results.html#result-arrays
Hope this helps
First u can create OrderModel to work with order table. Then create function get_order_data.
//Order Model
public function get_orders() {
// your db query to get orders
return $result;
}
Then u can load model in controller using $this->load->model('OrderModel'); Best place is __construct to load model
And call your get_orders() function
// Your controller
// Create data array to store front data
$data = [];
$data['orders'] = $this->OrderModel->get_orders();
After getting $orders pass it to view using following codes
$this->load->view('path/to/view', $data);
Finally u can call your order data in view using $orders
I hope this will help u
You need to set alias to the table to function it properly like this.
$this->db->select('a.*,a.order_details_id, b.order_id ', false);
$this->db->from('tbl_order_details as a');
$this->db->join('tbl_order as b', 'a.order_id = b.order_id ', 'left');
If you want select 1 row only you need to use this function.
$this->db->get('tbl_order_details')->row_array();
or if you want all result row you need to use this.
$this->db->get('tbl_order_details')->result_array();
On your controller you should add this lines to pass your result on your view page.
public function index()
{
$data['orderDetails'] = $this->your_model->get_order_return_info();
$this->load->view('pages/yourview/index',$data);
}
And finally to set your order details to the text boxes. You need to echo it inside the text boxes like this.
<input type="Text" name="orderID" value="<?php echo $orderDetails['order_id'];?>" >
If you use result_array() you need to use foreach loop to echo it.

How to get users list in codeigniter?

I am trying to get list of users from Users table in codeigniter. My problem is that if am using following code than try to print out the result, it's giving me blank array while printing query using last_query() function and running this query in phpmyadmin is giving correct result.
My code in model
$data = $this->db->select('u.*')
->from('users u')
->join('users_groups ug','ug.user_id = u.id')
->join('groups g','g.id = ug.group_id')
->where('g.id',7)
->get()
->result();
this code is giving me blank array then what i did is print the query using following code
echo $this->db->last_query();
and this is what query was
SELECT `u`.* FROM `users` `u` JOIN `users_groups` `ug` ON `ug`.`user_id` = `u`.`id` JOIN `groups` `g` ON `g`.`id` = `ug`.`group_id` WHERE `g`.`id` = 7
which is working fine. but i am trying to print the data using print_r($data)
is giving me blank array.
Can anyone tell me what can be the issue ?
edited
My full model code.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Technician_model extends CI_Model {
public function _consruct(){
parent::_construct();
}
function getData(){
$data = $this->db->select('u.*')
->from('users u')
->join('users_groups ug','ug.user_id = u.id')
->join('groups g','g.id = ug.group_id')
->where('g.id',7)
->get()
->result();
return $data;
}
function getRecord($user_id){
$record = $this->db->get_where('users',array('id'=>$user_id))->row();
echo '<pre>';
print_r($record);
exit;
return $record;
}
function addModel($data){
if($this->db->insert('users',$data)){
return $this->db->insert_id();
}
else{
return FALSE;
}
}
function editModel($data,$user_id){
$this->db->where('id',$user_id);
if($this->db->update('users',$data)){
return true;
}
else{
return false;
}
}
function deleteModel($user_id){
$this->db->where('id', $user_id);
if($this->db->delete('users')){
return true;
}
else{
return FALSE;
}
}
}
?>
You may try this simple way to join table. you may try this and can
change fields name table name and method according to your
require.
public function getUser() {
$this->db->select('users');
$this->db->from('Users');
$this->db->where('users_groups.user_id',1);
$this->db->join('users_groups', 'users.id = users_groups.user_id');
$query = $this->db->get();
$result = $query->result_array();
var_dump($result); // display data in array();
return $result;
}
Actually, at the end of 2 hrs of the journey, I found that I forgot to configure new database.
All the answers were correct in this case.

How to get to join table Codeigniter

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

Doctrine/MySQL: field missing in ResultSetMapping

I have a native query an want to fill a ResultSetMapping object with the results of my query.
Everything works as expected, but the field "distance". The field in the resulting array is always empty. When i run my query directly in MySQL there are results for "distance", so i guess my SQL is ok?
class PlaceRepository extends EntityRepository
{
public function getAllWithMainImage($lat, $lon)
{
try
{
$rsm = new ResultSetMapping;
$rsm->addScalarResult('slug', 'slug');
$rsm->addScalarResult('title', 'title');
$rsm->addScalarResult('rating', 'rating');
$rsm->addScalarResult('visited_at', 'visited_at');
$rsm->addScalarResult('img', 'img');
$rsm->addScalarResult('distance', 'distance');
return $this->getEntityManager()
->createNativeQuery('SELECT p.slug, p.title, p.rating, p.visited_at, pp.file AS img, ROUND(GLength(
LineString(
p.place_point,
GeomFromText("POINT(:lat :lon)")
)
) * 111.12, 1) AS distance
FROM place p
LEFT JOIN place_picture AS pp
ON p.id = pp.place_id
GROUP BY p.id
ORDER BY distance
LIMIT 20', $rsm)
->setParameter('lat', $lat)
->setParameter('lon', $lon)
->getResult();
}
catch(\Doctrine\ORM\NoResultException $e)
{
return false;
}
}
}
Repository function called from Crontroller:
class PlaceRestController extends Controller
{
public function getPlacesAction(ParamFetcher $paramFetcher)
{
$view = FOSView::create();
$view->setHeader('Access-Control-Allow-Origin', '*');
$em = $this->getDoctrine()->getManager();
$data = $em->getRepository('TouringPlaceBundle:Place')->getAllWithMainImage(48.39227479328352, 9.985520839691162); //hard-coded for debugging
print_r($data); //… [img] => xzz.jpg, [distance] =>
if($data)
{
$view->setStatusCode(200)->setData($data);
}
return $view;
}
}
Where is my mistake?
Can you add the part of your code where you are calling this method?
Where does the return value go? In an entity?
Evenf if I don't think so, the problem might come from the multiples quotes so :lat and :lon are not changed into the values you want them to be. Have you checked the profiler to be sure they are replaced?

Categories