for example i have one table about amount of money and the amount can increase or decrease .
the table currency_unit is :
id = 1
name = dollar
amount = 1000
the amount of update is :
$change = 5000;
for updating the table i have to write two query the first get data from table and the second update that with new data.
i use query builder class
the controller is :
$base = $this->base_model->get_data('currency_unit' , 'amount' , array('id'=> 1));
$data['amount'] = $base->amount + $change; // 1000 + 5000 = 6000
$this->base_model->update_data('currency_unit' , $data , array('id'=> 1));
the model is :
function get_data($table , $select , $where){
$this->db->select($select);
$this->db->where($where);
$result = $this->db->get($table);
return $result->row();
}
function update_data($table , $data , $where){
$this->db->where($where);
$this->db->update($table , $data);
}
Is there any way i update amount with one query not two query?
Try this hope it will work
$this->db->set('amount', 'amount+500', FALSE);
OR
$this->db->set('amount', 'amount+'.$change, FALSE);
$this->db->where('id', 1);
$this->db->update('currency_unit');
Related
The idea is I have a table events:
The column Mark_id has a relationship with another table called mark_events :
The relation in model Event :
public function markevent()
{
return $this->belongsTo('App\MarkEvent', 'mark_id', 'id');
}
What I need is count these columns ( status , diabetes , number_mark_event ) and save the total of these number in sum column
Code of Controller:
$form = [
'mark_id' => $request->mark_id,
'status' => $z,
'diabetes' => $request->diabetes,
];
$event = Event::update($form);
Join the tables and count the columns. This works as you only retrieve the counted columns, joins can provide side effect if returning ambiguous columns.
$eventCounts = Event::leftJoin('mark_events', 'events.mark_id', '=', 'mark_events.id')
->select(DB::raw('count(status) as status_count'), DB::raw('count(diabetes) as diabetes_count'), DB::raw('cout(number_mark_event) as number_mark_event_count'))
->get();
$eventCounts->status_count;
$eventCounts->diabetes _count;
$eventCounts->number_mark_event_count;
I write this solution for the example you posted
In update method in Controller:
public function update(Request $request){
$event = Event::where('mark_id',$request->mark_id)->firstOrFail();
$sum = $event->status + $event->diabetes + $event->markevent->number_mark_event;
$event->update([
'sum' => $sum
]);
Carts table columns :
'id',
'user_id',
'sp_id',
'service_id',
'dryclean',
'q_Shirt',
'q_Pant',
'q_Tie'
Pricing table column :
'id'
'sp_id'
'Shirt'
'Pant'
'Tie'
Both table do not have any relationship defined.
In cart controller
public function cart($sp_id, $service_id)
{
$prices = DB::table('pricings')->where('pricings.sp_id', '=', $sp_id)->get();
$cart = DB::table('carts')->where('carts.service_id', '=' , $service_id)->where('carts.sp_id','=', $sp_id)->where('user_id', '=' , auth()->id())->orderBy('id', 'desc')->take(1)->get();
return view('user.cart')->with('prices', $prices)->with('cart', $cart);
}
How do I calculate total amount of order?
If column dryclean has value of none then total is 0.
else total will be
(
carts->q_Shirt*prices->Shirt +
carts->q_Pant*prices->Pant +
carts->q_Tie*prices->Tie
)
This code is just for understanding of how I am calculating total
Please help me write code in laravel controller to calculate total and how to display it in view.
I don't think to understand you well, but you can try this to have some idea.
$prices = DB::table('pricings')
->where('pricings.sp_id', '=', $sp_id)
->get();
$cart = DB::table('carts')
->where('carts.service_id', '=' , $service_id)
->where('carts.sp_id','=', $sp_id)
->where('user_id', '=' , auth()->id())
->orderBy('id', 'desc')->take(1)
->get();
$total = 0;
$prices->reduce(function($acc, $current) use ($cart, &$total) {
return $total += ($current->Shirt + $cart->q_Shirt) +
($current->Pant + $cart->q_Pant) +
($current->Tie + $cart->q_Tie);
});
I am calculating the distance of a teacher from a school.
I am querying the user table and then the userable_type teacher using whereHas(). The teacher table has the longitude and latitude values.
The following worked for me elsewhere when I query the teacher model directly but not when querying through the user model first!
$query = User::where('userable_type', 'App\Teacher');
$query->with('userable');
if($school->latitude == '' || $school->longitude == '') {
\Session::flash('warning', 'Please check your school profile postcode; it appears that the system was unable to geocode your postcode! Results shown do not reflect any distances of staff from your school!');
} else {
$query->whereHas('teacher', function ($query) use ($school) {
$haversine = "(3961 * acos(cos(radians($school->latitude))
* cos(radians(latitude))
* cos(radians(longitude)
- radians($school->longitude))
+ sin(radians($school->latitude))
* sin(radians(latitude))))";
$query->select() //pick the columns you want here.
->selectRaw("{$haversine} AS distance")
->whereRaw("{$haversine} < ?", '20');
// ->havingRaw('{$haversine}', '<', '20');
});
}
$query->whereDoesntHave('thisSchool');
$teachers = $query->get();
The 'distance' field is not created but no errors are thrown! So my question is, in this scenario, how do I add the 'distance' value to each user as I would like to order by the distance?
This is the query where the Teacher model is queried directly, and it works!
$query = Teacher::with('user', 'user.schools', 'criterias', 'criterias.stafftype', 'criterias.teachingstage', 'criterias.teachingsubject')
->where('public', 1)
->where('verified', 1);
if($school->latitude == '' || $school->longitude == '') {
\Session::flash('warning', 'Please check your school profile postcode; it appears that the system was unable to geocode your postcode! Results shown do not reflect any distances of staff from your school!');
} else {
if( $filters['distance'] != '' ) {
$haversine = "(3961 * acos(cos(radians($school->latitude))
* cos(radians(latitude))
* cos(radians(longitude)
- radians($school->longitude))
+ sin(radians($school->latitude))
* sin(radians(latitude))))";
$query->select() //pick the columns you want here.
->selectRaw("{$haversine} AS distance")
->whereRaw("{$haversine} < ?", [$filters['distance']]);
}
}
$query->orderBy( 'active', 'DESC' );
$query->orderBy( 'distance', 'ASC' );
$teachers = $query->paginate( $filters['perpage'] );
Thanks,
K...
OK, I found a work-around for this problem and it can be found here:
Laravel 5 eloquent - add child field to parent model
I'd like to know the position of a user based on its creation date. How do I do that using Eloquent?
I'd like to be able to do something like this:
User::getRowNumber($user_obj);
I suppose you want MySQL solution, so you can do this:
DB::statement(DB::raw('set #row:=0'));
User::selectRaw('*, #row:=#row+1 as row')->get();
// returns all users with ordinal 'row'
So you could implement something like this:
public function scopeWithRowNumber($query, $column = 'created_at', $order = 'asc')
{
DB::statement(DB::raw('set #row=0'));
$sub = static::selectRaw('*, #row:=#row+1 as row')
->orderBy($column, $order)->toSql();
$query->remember(1)->from(DB::raw("({$sub}) as sub"));
}
public function getRowNumber($column = 'created_at', $order = 'asc')
{
$order = ($order == 'asc') ? 'asc' : 'desc';
$key = "userRow.{$this->id}.{$column}.{$order}";
if (Cache::get($key)) return Cache::get($key);
$row = $this->withRowNumber($column, $order)
->where($column, '<=',$this->$column)
->whereId($this->id)->pluck('row');
Cache::put($key, $row);
return $row;
}
This needs to select all the rows from the table till the one you are looking for is found, then selects only that particular row number.
It will let you do this:
$user = User::find(15);
$user->getRowNumber(); // as default ordered by created_at ascending
$user->getRowNumber('username'); // check order for another column
$user->getRowNumber('updated_at', 'desc'); // different combination of column and order
// and utilizing the scope:
User::withRowNumber()->take(20)->get(); // returns collection with additional property 'row' for each user
As this scope requires raw statement setting #row to 0 everytime, we use caching for 1 minute to avoid unnecessary queries.
$query = \DB::table(\DB::raw('Products, (SELECT #row := 0) r'));
$query = $query->select(
\DB::raw('#row := #row + 1 AS SrNo'),
'ProductID',
'ProductName',
'Description',
\DB::raw('IFNULL(ProductImage,"") AS ProductImage')
);
// where clauses
if(...){
$query = $query->where('ProductID', ...));
}
// orderby clauses
// ...
// $query = $query->orderBy('..','DESC');
// count clause
$TotalRecordCount = $query->count();
$results = $query
->take(...)
->skip(...)
->get();
I believe you could use Raw Expresssions to achieve this:
$users = DB::table('users')
->select(DB::raw('ROW_NUMBER() OVER(ORDER BY ID DESC) AS Row, status'))
->where('status', '<>', 1)
->groupBy('status')
->get();
However, looking trough the source code looks like you could achieve the same when using SQLServer and offset. The sources indicates that if you something like the following:
$users = DB::table('users')->skip(10)->take(5)->get();
The generated SQL query will include the row_number over statement.
[For Postgres]
In your model
public function scopeWithRowNumber($query, $column = 'id', $order = 'asc'){
$sub = static::selectRaw('*, row_number() OVER () as row_number')
->orderBy($column, $order)
->toSql();
$query->from(DB::raw("({$sub}) as sub"));
}
In your controller
$user = User::withRowNumber()->get();
What is the correct way to retrieve the last row, sorted desc by id, in CodeIgniter?
I've tried select_max but I want the whole row.
function getLastPagination(){
$data = array();
$this->db->query("SELECT id,sort FROM pagination GROUP BY id DESC LIMIT 1");
$query = $this->db->get('pagination');
$data = $query->row_array();
return $data;
}
$data['allpag'] = $this->Model_cats->getLastPagination();
$data['pagin'] = $data['allpag']['sort'];
$per_page = $data['pagin'];
Here I am getting the first value, but I want the last row.
$this->db->select('id')->order_by('id','desc')->limit(1)->get('table_name')->row('id');
Try this.............
function getLastPagination(){
$query ="select * from pagination order by id DESC limit 1";
$res = $this->db->query($query);
if($res->num_rows() > 0) {
return $res->result("array");
}
return array();
}
}
In controller function you need to do following things.......
$allpag = $this->Model_cats->getLastPagination();
$per_page = $allpag[0]['sort'];
$query = $this->db->query("SELECT * FROM pagination ORDER BY id DESC LIMIT 1")->row_array();
Should work?