how to select query tables column with objects in query builder - sql

i am joining two tables with query builder. here is the sample
$events = DB::table('eventcalenders')
->select('eventcalenders.id','eventcalenders.event_name',)
->join('countries', 'eventcalenders.country_id', '=', 'countries.id')->get();
can i declare an object of eventcalender as e and select with object name like 'e.id','e.event_name'.?

Yes, after the query you need to loop through them since they are more than one item:
foreach($events as $e){
$name = $e->event_name;
}
If you want to select only the first one that meets your constrains then use .first().
$event = DB::table('eventcalenders')
->select('eventcalenders.id','eventcalenders.event_name',)
->join('countries', 'eventcalenders.country_id', '=', 'countries.id')->first();
$name = $event->event_name;

$events = DB::table('eventcalenders')
->select('eventcalenders.id','eventcalenders.event_name','countries.*')
->join('countries', 'eventcalenders.country_id', '=', 'countries.id')
->get();
Afetr getting results
foreach($events as $event)
{
echo $event->event_name;
echo $event->country_name; //your specific field
}

Related

how to add new field & value from selected joined table

i have a joined table like this
i want to create new field named qty_exceed and the value is based from
(qty_stock - qty_taken)
do i have to do it in the query or make separate operation and store it in a varible?
my code
$getmaterial = ContractProduct::select(
'product_item.ref_rof_id',
'product_item.code',
'product_item.qty_stock',
'contract_product.qty_taken'
)
->where('ref_rof_id', $getrof->ref_rof_id)
->join('product_item', 'contract_product.ref_product_id', '=', 'product_item.code')
->get();
$data['getquoid'] = $getquoid;
$data['getmaterial'] = $getmaterial;
$view = $this->module_path . '.next-create';
return response()->view($view, $data);
You need to use DB::raw
But remember, raw statements will be injected into the query as strings, so you should be extremely careful to not create SQL injection vulnerabilities.
With DB::raw your code will look like this:
$getmaterial = ContractProduct::select(
'product_item.ref_rof_id',
'product_item.code',
'product_item.qty_stock',
'contract_product.qty_taken',
ContractProduct::raw('product_item.qty_stock - contract_product.qty_taken as qty_exceed')
)
->where('ref_rof_id', $getrof->ref_rof_id)
->join('product_item', 'contract_product.ref_product_id', '=', 'product_item.code')
->get();
$data['getquoid'] = $getquoid;
$data['getmaterial'] = $getmaterial;
$view = $this->module_path . '.next-create';
return response()->view($view, $data);

Select sql code in Laravel

Following query returning six values
SELECT tbl_start FROM timetable inner join route ON tbl_rte_id = id WHERE rte_origin = "UL" and rte_destination = "HW" ORDER BY(tbl_start) DESC;
And my laravel code is returning only one value
$tables = Timetable::join('route', 'tbl_rte_id', '=', 'id')
->where('rte_origin', $origin, 'AND')
->where('rte_destination', $destination)
->orderBy('tbl_start', 'desc')
->get();
foreach ($tables as $table) {
$result[$table->id] = $table->tbl_start;
}
This laravel code is not similar or similar. Can anyone help me.
Change this part:
->where('rte_origin', $origin, 'AND')
// to:
->where('rte_origin', $origin)
It will know by default that it's AND operator
And if you want to provide this operator, then do this:
->where('rte_origin', '=', $origin, 'AND')
You may try something like this:
$tables = Timetable::join('route', 'tbl_rte_id', '=', 'timetable.id')
->where('rte_origin', $origin)
->where('rte_destination', $destination)
->orderBy('tbl_start', 'desc')
->get()->lists('tbl_start', 'id');
The $tables will contain an array of id => tbl_start pairs.
Add a listener in your routes.php
Event::listen('illuminate.query', function($sql){
var_dump($sql);
});
Then execute both queries and check if you have the same result

$data = $query->row(); returns only one row

Im trying to list the results of my sql query (picking up all the movies from a category), but I cannot figure out how to get all the rows instead of only one.
Here's the code :
$this->load->database();
$sql = 'SELECT * FROM movies WHERE category = "'.$movies_category.'";';
$query = $this->db->query($sql);
$data = $query->row();
$this->response($data, 200);
I've tried :
while($row = mysql_fetch_assoc($query)){
$data = $query->row();
}
$this->response($data, 200);
And it doesn't work. Any suggestion ? Thank you !
$this->load->database();
$sql = 'SELECT * FROM movies WHERE category = "'.$movies_category.'";';
$query = $this->db->query($sql);
$data = $query->result();
To traverse the $data array:
foreach($data AS $row)
{
//to retrieve the data from each row.
$col1 = $row->col1;
$col2 = $row->col2;
}
Use result() instead of row(). result() will return an array of objects that are your results. Alternatively, you can useresult_array() which will resturn an array of arrays keyed according to your columns. Please refer to here for a better outline of the result() and row() methods.
Do you have a database configuration file? the load->database() requires it. Where is $movies_category coming from? This will let you iterate over your results.
$this->load->database();
$sql = 'SELECT * FROM movies WHERE category = "'.$movies_category.'";';
$query = $this->db->query($sql);
foreach ($query->result() as $row)
{
echo $row->column;
}
Where column corresponds with one of the values in the movies table.
I'm surprised nobody has mentioned the potential hazards of using variables (possibly user input) in your SQL. You should seriously consider using query bindings or the active record features of CodeIgniter to build safer queries.
Consider the following solution to your problem:
$this->load->database();
$sql = 'SELECT * FROM movies WHERE category = ?';
$query = $this->db->query($sql, array($movies_category));
// $data = $query->result(); // returns result as an array of objects
$data = $query->result_array(); // returns result as array
$this->response($data, 200);
I'm assuming this is for some sort of API? If so, consider using the result_array() method as it will probably be better suited for your needed output, and also really easy to convert into JSON:
$json_data = json_encode($data);
Hope that helps,
Cheers.
For your question row() return only one value its good for checking in ID and if you want get all the rows use result_array() or simple result()
You can try this code....
Model:
function get_movies($movies_category){
$this->db->where("category",$movies_category);
$query = $this->db->get("movies");
return $query->result_array();
}
Controller:
$this->data['movies'] = $this->'name of model'->get_movies('here is the movie categories');
View:
foreach($movies as $m){
print_r($m);
}
exit();
Note you can directly add the code in function in model to controller add this in your controller if you want directly...
$this->data['movies] = $this->db->get('movies')->result_array();

kohana orm join duplicate objects result

I'm trying to query the country table with the below query to print all countries with the corresponding cities. Now i'm getting a duplicated country object for each city instead of have one country object for all cities.
$all = ORM::factory('country')->select('cities.*')->join('cities','LEFT')->on('country.id', '=', 'country_id' )->find-all();
foreach ($all as $country) {
echo $caountry->name;
foreach($country->cities as $city ){
echo $city->name;
}
}
Appreciate your help,
AA
If you are using MySQL and only need the name of the city, you can use GROUP_CONCAT function and then convert it to array using PHP's explode.
$all = ORM::factory('country')
->select('country.name',DB::epxr('GROUP_CONCAT(cities.name) AS cities'))
->join('cities','LEFT')
->on('country.id', '=', 'country_id' )
->group_by("country.id")
->find-all();
foreach ($all as $country) {
echo $country->name;
foreach(explode(",",$country->cities) as $city ){
echo $city;
}
}

Yii: adding custom fields

Is there a simple way of adding custom fields to a model? Say I have a table "user" with 3 fields: id, name and surname. I want this:
$user = User::model()->findByPk(1);
$echo $user->fullName; // echoes name and surname
Please note: I want this custom field to be added via sql, smth like
$c = new CDbCriteria();
$c->select = 'CONCAT("user".name, "user".surname) as fullName';
$user = User::model()->find($c);
Problem is that fullName property is not set.
UPD:
here is the code for a little bit trickier problem -- custom field from another table. This is how it's done:
$model = Application::model();
$model->getMetaData()->columns = array_merge($model->getMetaData()->columns, array('fullName' => 'CONCAT("u".name, "u".surname)'));
$c = new CDbCriteria();
$c->select = 'CONCAT("u".name, "u".surname) as fullName';
$c->join = ' left join "user" "u" on "t".responsible_manager_id = "u".id';
$model->getDbCriteria()->mergeWith($c);
foreach ($model->findAll() as $o) {
echo '<pre>';
print_r($o->fullName);
echo '</pre>';
}
You can add a function to the User class:
public function getFullName() { return $this->name.' '.$this->surname; }
This will return the full name as if it were an attribute from the database. This is much easier than adding a calculated column to the SQL.
In model
public function getMetaData(){
$data = parent::getMetaData();
$data->columns['fullName'] = array('name' => 'fullName');
return $data;
}
Thus not recommended