I am trying to update a laravel collection with another collection. Here are my collections :
$acc = DB::table('accounts')
->where('accounts.branchid', $branch_id)
->select('code','title','opbal','clbal')->get();
$rslt = DB::table('journal')
->where('journal.branchid', $branch_id)
->where(function($q) {$q->where('journal.cancel','!=',1)->orWhereNull('journal.cancel');})
->select('code',DB::raw('sum(IFNULL(dr,0) - IFNULL(cr,0)) as total'))->groupBy('code')->Get('code','total');
What I want is to update $acc->clbal with $rslt->total where $acc->code = $rslt->code
I tried this but it does not work
foreach ($rslt as $row) {
$getacc = $acc->where('code',$row->code);
$getacc->clbal = $row->total;
}
Here is the solution.
$acc = DB::table('accounts')
->where('accounts.branchid', $branch_id)
->select('code','title','opbal','clbal')->get();
$rslt = DB::table('journal')
->where('journal.branchid', $branch_id)
->where(function($q) {$q->where('journal.cancel','!=',1)->orWhereNull('journal.cancel');})
->select('code',DB::raw('sum(IFNULL(dr,0) - IFNULL(cr,0)) as total'))->groupBy('code')->Get('code','total');
foreach ($rslt as $row) {
$getacc = $acc->where('code',$row->code)->first();
$getacc->update(['clbal' => $row->total]);
}
Related
i'm try to foreach inside the foreach to get the count data with this code
Controller.php
$jadwals = DB::table('tb_jadwal')->get();
foreach ($jadwals as $key => $jadwal) {
$tgl = date("Y-m-d", strtotime($request->tgl));
$cek_tiket = array();
$cek_tiket = DB::table('tb_tiket')
->select(DB::raw('count( distinct id_tiket) as jumlah_kapasitas'))
->where('Tgl_Berangkat', '=', "'$tgl'")
->where('id_jadwal', '=', $jadwal->id_jadwal)
->get();
$jadwals[$key]->jumlah_kapasitas = $cek_tiket;
}
view.blade.php
#foreach($cek_tiket as $cek_tiket)
<?php
if ($cek_tiket->jumlah_kapasitas <= 70) {
echo "There data";
dd($cek_tiket);
}
?>
#endforeach
but the result of dd is 0
I have composed a query using Codeigniter's Query Builder class. The query utilizes aliases and the having method. When I call the count_all_results method on this query, an exception occurs. Inspecting the log, I see that the query has stripped out the 'having' clauses. Is there a way to keep these clauses in while calling count_all_results? Thanks for your help.
EDIT: I first believed the problem was knowledge-based and not code-based and so did not share the code, but here it is. Please let me know if more is needed.
Here's the call on the model in the controller.
$where_array = array(
$parent_key.' is not NULL' => null
);
$search_post = $request_data['search'];
if (isset($request_data['filter'])) {
$filter_array = $request_data['filter'];
foreach ($filter_array as $filter_pair) {
if (isset($filter_pair['escape'])) {
$where_array[$filter_pair['filterBy']] = null;
} else {
if ($filter_pair['filterBy'] == 'table3_id') {
$where_array['table3.'.$filter_pair['filterBy']] = isset($filter_pair['filterId']) ?
$filter_pair['filterId'] : null;
} else {
$where_array[$table.'.'.$filter_pair['filterBy']] = isset($filter_pair['filterId']) ?
$filter_pair['filterId'] : null;
}
}
}
}
$like_array = array();
foreach ($request_data['columns'] as $key => $column) {
if (!empty($column['search']['value'])) {
$like_array[$column['data']] = $column['search']['value'];
}
}
$totalFiltered = $this->$model_name->modelSearchCount($search, $where_array, $like_array);
Here's the model methods.
public function modelSearchCount($search, $where_array = null, $like_array = null)
{
$this->joinLookups(null, $search);
if ($where_array) {
$this->db->where($where_array);
}
if ($like_array) {
foreach($like_array as $key => $value) {
$this->db->having($key." LIKE '%". $value. "%'");
}
}
return $this->db->from($this->table)->count_all_results();
}
protected function joinLookups($display_config = null, $search = null)
{
$select_array = null;
$join_array = array();
$search_column_array = $search ? array() : null;
$i = 'a';
$config = $display_config ? $display_config : $this->getIndexConfig();
foreach ($config as $column) {
if (array_key_exists($column['field'], $this->lookups)) {
$guest_model_name = $this->lookups[$column['field']];
$this->load->model($guest_model_name);
$join_string =$this->table.'.'.$column['field'].'='.$i.'.'.
$this->$guest_model_name->getKey();
$guest_display = $this->$guest_model_name->getDisplay();
if ($search) {
$search_column_array[] = $i.'.'.$guest_display;
}
$join_array[$this->$guest_model_name->getTable().' as '.$i] = $join_string;
$select_array[] = $i.'.'.
$guest_display;
} else {
$select_array[] = $this->table.'.'.$column['field'];
if ($search) {
$search_column_array[] = $this->table.'.'.$column['field'];
}
}
$i++;
}
$select_array[] = $this->table.'.'.$this->key;
foreach ($join_array as $key => $value) {
$this->db->join($key, $value, 'LEFT');
}
$this->db->join('table2', $this->table.'.table2_id=table2.table2_id', 'LEFT')
->join('table3', 'table2.table3_id=table3.table3_id', 'LEFT')
->join('table4', $this->table.'.table4_id=table4_id', 'LEFT')
->join('table5', 'table4.table5_id=table5.table5_id', 'LEFT');
$this->db->select(implode($select_array, ', '));
if ($search) {
foreach (explode(' ', $search) as $term) {
$this->db->group_start();
$this->db->or_like($this->table.'.'.$this->key, $term);
foreach ($search_column_array as $search_column) {
$this->db->or_like($search_column, $term);
}
$this->db->group_end();
}
}
$this->db->select('table2_date, '. $this->table.'.table2_id, table4_id, '. 'table5.table5_description');
}
Since count_all_results() will basically run a Select count(*) and not count the rows in your resultset (basically rendering the query useless for your purposes) you may use other Codeigniter methods to get the resultset and the row count.
Try running the query into a variable:
$query = $this->db->get();
From then, you can do pretty much anything. Besides returning the result with $query->result(); you can get the number of rows into another variable with:
$rownum = $query->num_rows();
You can then return that into your controller or even just return the $query object and then run the num_rows() method on the controller
To answer this question, count_all_results() transforms the original query by replacing your selects with SELECT COUNT(*) FROM table. the aliased column would not be selected, and the having clause would not recognize the column. This is why count_all_results() does not work with having.
I use the following code to get data from two related tables:
$arr = [];
$objectModel = new ProductCategory();
$objectModel::$language = 2;
$subcategories = $objectModel::with("translate", "parent")->get();
foreach($subcategories as $key => $item) {
$arr[$item->translate()->first()->objectId] = $item->translate()->first()->name;
}
array_unshift($arr, 'Select category');
return $arr;
In result this part of code I get array with key => value to insert this in select list in Blade template.
But I desire to escape a loop:
foreach($subcategories as $key => $item) {
$arr[$item->translate()->first()->objectId] = $item->translate()->first()->name;
}
And get clear collection from request. How can I do it?
You can use Laravel Collections https://laravel.com/docs/5.3/collections
$arr = ProductCategory::with("translate", "parent")->get()
->mapWithKeys(function ($item, $key) {
return [$item->translate()->first()->objectId => $item->translate()->first()->name];
})
->all();
I'm building a filter function in a project.
I have a filter option "Show newest", "Show oldest" and a bunch of other options. I found a way how to implement conditional where clauses, but there doesn't seems to be a conditional orderBy class.
My conditional where clause looks like this:
$query->where(function($query) use ($request){
if( ! empty($request->input('prices')) ){
$opts = $request->prices;
$query->where('price_id', $opts[0]);
}
})
Is there a way to do this with a ->orderBy too?
UPDATE
return Auction::where('end_date', '>', Carbon::now() )
->where('locale', $locale)
->where('sold', 0)
->where(function($query) use ($request){
if( ! empty($request->input('prices')) ){
$opts = $request->prices;
$query->where('price_id', $opts[0]);
}
})->paginate(8);
How can I do it in the eloquent-way?
Of course, you can do it this way:
if ($request->input('id_desc')) {
$query = $query->orderBy('id', 'DESC');
}
or you can do it this way:
$columns = ['id','name',]; // here define columns you allow for sorting
$orderBy = ['ASC', DESC'];
$column = $request->input('order_by_column');
$type = $request->input('order_by_type');
if (!in_array($column, $columns)) {
$column = 'id';
}
if (!in_array($type , $orderBy )) {
$type = 'ASC';
}
$query = $query->orderBy($column, $type);
EDIT
Using your code:
$query = Auction::where('end_date', '>', Carbon::now() )
->where('locale', $locale)
->where('sold', 0)
->where(function($query) use ($request){
if( ! empty($request->input('prices')) ){
$opts = $request->prices;
$query->where('price_id', $opts[0]);
}
});
if ($request->input('id_desc')) {
$query = $query->orderBy('id', 'DESC');
}
return $query->paginate(8);
I am trying to use AND as well as && in this code block:
public function show($id)
{
$user = Auth::user()->id;
$userEmail = Auth::user()->email;
$share = Share::where('sbj_id', $id)->first();
if ($share->sbj_id == $id && $share->email == $userEmail ) {
$items = Item::where('project_id', $id)
->orderBy("created_at", "desc")
->groupBy('label_name')
->get();
$sbj = Sbj::find($id);
$allSbj = Sbj::where('user_id', $user)->orderBy("created_at", "desc")->get();
$labels = Label::all();
$pages = Page::where('project_id', $id)->orderBy('created_at', 'desc')->get();
$people = Friend::where('sbj_id', $id)->orderBy("created_at", "desc")->get();
$myPeeps = Contact::where('my_id', $user)->get();
return View::make('sbjs.show', compact('sbj', 'pages', 'labels', 'people', 'myPeeps', 'allSbj', 'items'));
} else {
return Redirect::action ('SbjsController#index');
}
}
However, I am looking online to see if && or AND is supported in Lavavel in this context but no success. My app is taking the user to the ELSE action.
Any ideas?
I just added the Eloquent statement to the IF conditional and it worked fine...not sure why it was not evaluating.