Selecting a single column from model to controller in codeigniter3.0.0 - php

I am new in codeigniter.
I need only the available column from the model than what code I write in the controller to get a single column
My model code is:
public function check_reservation($restaurant_id,$date,$people,$start_time,$end_time){
$sql="SELECT
r.restaurant_id,r.restaurant_name,r.capacity,rs.start_time,rs.end_time,rs.people,rs.date,r.capacity - SUM(IFNULL(rs.people,0)) AS available FROM restaurant r
LEFT JOIN reservation rs ON r.restaurant_id = rs.restaurant_id
AND ".$date." = rs.`date`
AND ".$people." = rs.`people`
AND '".$start_time."' = rs.`start_time`
AND '".$end_time."' = rs.`end_time`
WHERE r.restaurant_id = ".$restaurant_id."
GROUP BY r.`restaurant_id`";
$query=$this->db->query($sql);
return $query->result();
}
Thank you

It's not clear what you need. If you want to get only one column in the Controller, when you iterate with foreach (or for), you ask for your column name.
foreach ( $records as $record ) {
echo $record['restaurant_name'];
echo "<br/>";
}

Related

Laravel table joins

I'm trying to do some table joins and having some trouble.i need to display
the customer’s complete name and title, item description, quantity ordered, for each item ordered after April 2000. i made a SQL script that works but i need to use Laravel ORM.
SELECT `first_name`,`last_name`,o.order_id,`quantity`,`description`,`date_placed`
FROM `customer` c
JOIN `order` o
ON c.`customer_id` = o. `customer_id`
JOIN `orderline` ol
ON o.`order_id` = ol. `order_id`
JOIN `item` i
ON ol.`item_id` = i. `item_id`
WHERE `date_placed` > '2000-4-00';
I created 2 models for the tables "Customer", "Order"
here is my Customer model
public function orders(){
return $this->hasMany('App\Order','customer_id');
}
here is my order model
public function orderline(){
return $this->hasMany('App\Orderline','order_id');
}
right now i am able to get some of my data but i dont feel like this is a good way to go about
$customer = Customer::all();
foreach($customer as $input){
$item = Customer::find($input->customer_id)->orders;
$name = $input->title . ' ' . $input->first_name . ' ' . $input->last_name;
$datePlaced = null;
$orderID = null;
foreach($item as $value){
$orderID = $value->order_id;
$datePlaced = $value->date_placed;
$order = Order::find($value->order_id)->orderline;
}
if anyone could point me in the right direction that would be great.
It looks like you want to get all Customers with their Orders and OrderLines?
Customer::with(['order' => function ($query) {
$query->where('date_placed', '>=', '2000-04-01')->with('orderline');
}])->get();
If you want to limit the columns on the relationships, you can...
Customer::with(['order' => function ($query) {
$query->select(/* columns */)->where('date_placed', '>=', '2000-04-01')
->with(['orderline' => function ($query) {
$query->select(/* columns here */);
}]);
}])->get();
Just make sure if you specify the columns in the relationships, that you're selecting all of the foreign keys or related columns for each relationship.

How can I display fields from two different tables using active record of left join in codeigniter?

function get_all_notification() { //get all notification based on the 'notification' table left join by 'membership' table
$this->db->select()->from('notification')->join('membership','membership.membership_id = notification.notif_id','left'); $notif = $this->db->get();
return $notif->result();
}
I cannot display the fields from membership table.
Try this
function get_all_notification() { //get all notification based on the 'notification' table left join by 'membership' table
$this->db->select('*')->from('notification')->join('membership','membership.membership_id = notification.notif_id','left');
$notif = $this->db->get();
return $notif->result();
}
function get_all_notification()
{
$this->db->select('n.*,m.*');
$this->db->from('notification as n')
$this->db->join('membership as m','m.membership_id = n.notif_id','left');
$notif = $this->db->get();
return $notif->result();
}
This is used when you want a clean code that's from top to bottom. But using your code is fine to where as the arrows are continuous. You just forgot to identify which fields to select. Also using aliases are good in selecting specific fields.
as you can see, I used n.* and m.*, this is just a wildcard to select all from the n table and m. you can you n.your_field and m.your_field when specifying what you want.
Goodluck and have fun coding :D

get looping data from one data

I am using codeigniter.
I have two function in the model.
In the first function, I get all specific rows from one table. This is where I want to get all product details.
function getProduct()
{
$shoes = 'SELECT pd.name,
pd.id,
pd.price
FROM product_detail pd
LEFT JOIN product_sub_category psc
ON pd.sub_category_id = psc.id
WHERE psc.name = "Shoes"';
$categoried = $this->db->query($shoes);
return $categoried->result();
}
While in the second function, I get all specific rows based on one row from the first function. This is where I want to get all images for each products.
function getImage()
{
$shoes = 'SELECT pim.file_name
FROM product_img pim
LEFT JOIN product_detail pd
ON pim.product_detail_id = pd.id
WHERE pim.product_detail_id = "'.$row->id.'"';
$categoried = $this->db->query($shoes);
return $categoried->result();
}
But it gives me some errors.
Can someone please help me? Thanks for the help.
[UPDATE]
This is my Controller
In the controller, I identify records to get the product, and recorded to get the image.
function index()
{
$this->load->model('site_model');
$data = array();
$query = $this->site_model->getProduct();
$data['records'] = $query;
foreach ($query as $row)
{
$id = $row->id; // get ID
$name = $row->name; // get ID
$product_image = $this->site_model->getImage($id); // invoke the second method feeding that ID
$data['recorded'] = $product_image;
}
$this->load->view('mothershop', $data);
}
This is my Model
function getProduct()
{
$shoes = 'SELECT pd.name,
pd.id,
pd.price
FROM product_detail pd
LEFT JOIN product_sub_category psc
ON pd.sub_category_id = psc.id
WHERE psc.name = "Shoes"';
$categoried = $this->db->query($shoes);
return $categoried->result();
}
function getImage($id)
{
$shoes = 'SELECT pim.file_name
FROM product_img pim
LEFT JOIN product_detail pd
ON pim.product_detail_id = pd.id
WHERE pim.product_detail_id = "'.$id.'"';
$categoried = $this->db->query($shoes);
return $categoried->result();
}
This is my View of mothershop.php
In this section, I call the records and recorded
foreach ($records as $row)
{
echo "<div>".$row->name."</br>";
foreach ($recorded as $rowed)
{
echo "<img src='".base_url()."upload/thumbs/".$rowed->file_name."'/>";
}
echo "</div>";
}
However, I don't know why, it only get the same image for each products.
But if i print the $product_image in the controller, it gives me different images for each products.
What is wrong here?
Thanks in advance for #Ghost
Since that $row->id is solely depending on the first fetching method, currently, its out of scope. In order to use that ID from the first method, just add an argument on the second method and use that to the second query. More like this:
function getImage($id)
Then you can use it on the second method.
Since you haven't shown any code on how you are using your methods. Consider this example:
First method usage (Controller):
$this->load->model('Super_model');
$products = $this->Super_model->getProduct();
foreach($products as &$row) {
$id = $row->id; // get ID
$product_image = $this->Super_model->getImage($id); // invoke the second method feeding that ID
if(!empty($product_image)) { // if it exists
$row->file_name = $product_image->file_name; // add another property which is file_name on that first fetched data
}
}
Model method:
function getImage($id)
{
$shoes = "SELECT pim.file_name
FROM product_img pim
LEFT JOIN product_detail pd
ON pim.product_detail_id = pd.id
WHERE pim.product_detail_id = '$id' ";
$categoried = $this->db->query($shoes);
return ($categoried->num_rows() > 0) ? $categoried->row() : null;
}
That's the basic idea of it, we don't know what goes on and how you glue everything else on the controller, adjust it to fit into your codebase.

How to write query to count the foreign key in yii using CDbCriteria?

I have tables Ads with column AdsId,ClientId and table Assigned . Assigned has AdsId as foreign key. I want to count the number of AdsId in Assigned for given ClientId. I have the following query which works but I am not sure if its the best way. How can I run the same query in yii? Hope I made my question clear.
SELECT A. * , (
SELECT COUNT( B.AdsId )
FROM Assigned AS B
WHERE B.AdsId = A.AdsId
AND A.ClientId =1
)
FROM Ads AS A
WHERE A.ClientId =1
LIMIT 0 , 30
First declare a relation in your model relations function
public function relations(){
return array(
...
'AdsIdCount'=> array(self::STAT,'Ads','AdsId'),
//'VarName'=>array('RelationType', 'ClassName', 'ForeignKey', ...additional options)
);
}
then in your in returned activeRecord results you can just call this count like this
$result = Assigned::model()->find($criteria);
$result->adsIdCount ; // do logic here
or
$results = Assigned::model()->findAll($criteria);
foreach ($results as $result){
$result->adsIdCount ; // do logic here
}
see STAT relation for more details on how this works http://www.yiiframework.com/doc/guide/1.1/en/database.arr#statistical-query

ZF2 multiple tables join in one model, get columns from join table

So here is my query:
public function fetchAd($adID){
$row = $this->tableGateway->select(function(Select $select) use ($adID){
$select->join('adDetails','adDetails.adID = ads.adID',array('*'),'inner');
$select->where(array('ads.adID' => $adID));
});
return $row->current();
}
So what I'm doing I'm querying the ad table and join the adDetails table in order for me to get the details for a certain AD, the problem is that the entity AD which belongs to the model that I'm doing the query, it doesn't have the columns names(variables) from the adDetails table; so it will only return the columns from the AD table, because the entity doesn't have those fields in the exchangeArray()
I have tried to extend the AD entity to use the AdDetails entity but it returns now to object array but with the fields as null, because it can;t populate them.
So, how should I do this, in order for me to have all the columns available in the model for the tables that will join?
I'm planning to join other tables as well.
Ok I solved the problem, the thing is that it will return an array, and it won't use the ORM style, but it does the job, for now relations are not supported in ZF2 like in ZF1;
use Zend\Db\Sql\Sql,
Zend\Db\Sql\Where;
$sql = new Sql($this->tableGateway->getAdapter());
$select = $sql->select();
$select->from($this->tableGateway->table)
->join('adDetails','adDetails.adID = ads.adID',array('*'),'inner');
$where = new Where();
$where->equalTo('ads.adID', $adID) ;
$select->where($where);
$statement = $sql->prepareStatementForSqlObject($select);
$result = $statement->execute();
return $result->current();
public function fetchJoin()
{
$select = new \Zend\Db\Sql\Select;
$select->from('tablea a');
$select->columns(array('*'));
$select->join('tableb b', "b.id = a.b_id", array('field1'), 'left');
// to display query string remove comment in next line
//echo $select->getSqlString();
$resultSet = $this->tableGateway->selectWith($select);
return $resultSet;
}

Categories