laravel chunk (help) - php

when i using postman get the result from chunk,but the result will return empty,how can i solve this?
enter image description here
here's my code
public function downloadMemberInfo()
{
error_log('download');
set_time_limit(240); //testing
$memberListsArray = array();
Member::select('vipcode')->where('vipcode','!=','')
->chunk(3000,function($members) use($memberListsArray){
foreach($members as $member){
$memberListsArray[] = $member;
}
});
return response()->json($memberListsArray);
}

You need to call get before use chunk; because chunk works with collections. Try with the next code.
public function downloadMemberInfo()
{
error_log('download');
set_time_limit(240);
$members = Member::select('vipcode')
->where('vipcode', '!=', '')
->get()
->chunk(3000)
->toArray();
return response()->json($members);
}
By the way, I recommend you to use paginate or some query limit to avoid performance issues

Related

Laravel. Exporting results from database problems

As short as possible. My code runs through multiple databases counts objects and matches name - number of objects
It runs like a script(command in laravel) that exports the results in .csv file.
$formatted_data = array();
$providers = provider::where('del', 'no')->get();
foreach($providers as $provider){
$formatted_data[$provider['id']]['name'] = $provider['name'];
}
$objectMappingsModels = array((new objectMapping1), (new objectMapping2),
(new objectMapping3), (new objectMapping4), (new objectMapping5),
(new objectMapping6), (new objectMapping7), (new objectMapping8));
foreach($objectMappingsModels as $objectMappingsModel){
$totals = $objectMappingsModel::select('providerFK', DB::raw('count(*) as total'),
DB::raw('monthName(ut) as month_name')
)
->where('userFK', '!=', 1)
->where('del', 'no')
->whereMonth('ut', $this->option('month'))
->whereYear('ut', $this->option('year'))
->groupBy('providerFK', 'month_name')
->get()
->toArray();
foreach($totals as $total){
$formatted_data[$total['providerFK']]['count'] = $total['total'];
}
}
$responce = Excel::store(new UsersExport($formatted_data), 'testNameDate.csv',null, \Maatwebsite\Excel\Excel::CSV);
return true;
That's what my code looks like.
class UsersExport implements FromArray
{
protected $invoices;
public function __construct(array $invoices)
{
$this->invoices = $invoices;
}
public function array(): array
{
return $this->invoices;
}
}
And that's what my export class looks like.
Unfortunately, it's not working flawlessly. It gives me wrong results from time to time. Some records a correct and some are not. Also, the last row is always with just a random number(without a name attached to it). Any idea why such problems occur and can you suggest me some code optimizations?
Thanks!
I added this if-else in the last loop
if(isset($formatted_data[$total['providerFK']]['count'])){
$formatted_data[$total['providerFK']]['count'] += $total['total'];
}else{
$formatted_data[$total['providerFK']]['count'] = $total['total'];
}
And it seems to have fixed some issues

Laravel, when using Eloquent to retrieve data paginate and get methods are returning diferent output

I am having a hard time with Laravel. I have a query that returns all the table columns. The problem is that a field "foto" returns as an empty string in the JSON when I use the "get" or "find" methods. Paginate it works as expected.
This query:
$resultado = $query
->where('id_admin', '=', $id_admin)
->with('telasPermissao.itemPermissao')
->paginate(50);
foto comes as:
"foto": "data/image:93483940349"
Now, with this:
$resultado = $query
->where('id_admin', '=', $id_admin)
->with('telasPermissao.itemPermissao')
->find(1);
$resultado = $query
->where('id_admin', '=', $id_admin)
->with('telasPermissao.itemPermissao')
->get(50);
foto comes as:
"foto" : ""
I am returning the data from the controller like this:
return response()->json($resultado, 200);
In my operador model I have the following mutator:
public function getFotoAttribute($value)
{
if ($value != null)
{
return pg_escape_string(fgets($value));
}
return null;
}
Try updating your mutator like this:
public function getFotoAttribute()
{
if ($this->attributes['foto'] != null)
{
return pg_escape_string(fgets($this->attributes['foto']));
}
return null;
}
After fighting 2 hours, I give up. As a workoaround I used this to replace the find method.
$resultado = $query->where('id_admin', '=', $id_admin)->with('telasPermissao.itemPermissao')->where('id', 517 )->paginate(1)
If someone knows what happened please post an answer.

Laravel SQL with where not in example and gettype with dynamic value

There is one function for getting all the data from table with one where clause and one with not wherein clause. I am stuck when I am passing data dynamically but when I am hardcoding the data, it is showing me correct data.
Hard-coded Example :
public function getAllTickets($drawId, $existing)
{
$login = [200263129,200263162,200263735,200263752];
$data = $this->select('ticket')
->where('wlf_draws_id', $wlfDrawId)
->whereNotIn('login', $login)
->get();
return $data;
}
Dynamic Example :
public function getAllTickets($drawId, $existing)
{
$login = [$existing];
$data = $this->select('ticket')
->where('wlf_draws_id', $wlfDrawId)
->whereNotIn('login', $login)
->get();
return $data;
}
In variable $existing I am same data as 200263129,200263162,200263735,200263752
But result is varying for both data and hard-coded example is showing me correct result.
Please use this it may help you:
public function getAllTickets($drawId, $existing)
{
$login = explode(',',$existing);
$data = $this->select('ticket')
->where('wlf_draws_id', $wlfDrawId)
->whereNotIn('login', $login)
->get();
return $data;
}

sortBy and orderBy, isn't working in my code in Laravel

I want to get the latest timestamp. For some reason, when I try to use sortBy or orderBy, it doesn't work. Can anyone help me?
Here is the codes that I tried:
public function getTest($id) {
$data = test::where('user_id', $id)->sortByDesc('created_at')->get();
// I also tried doing this
$data = test::where('user_id', $id)->orderBy('created_at', 'desc')->get();
if(count($data)>0) {
return view('test', compact('data'));
}
else {
return view('test');
}
}
Try:
$data = test::where('user_id', $id)->orderBy('created_at', 'desc')->first();
This will order the rows in table by created_at.
Hope this helps you!
If you want to get the oldest created_at it would be easier to query like
$data = test::where('user_id', ,'=', $id)->oldest();
to get the user's test in descending order.
Here's a "pro" tip: You should set up a relation between Test und User. And typehint your method (your route would look like Route::get'(/users/{user}/tests', 'UserTestsController#index');. You then could write your query like:
public function index(User $user)
{
$data = $user->tests()->oldest();
return view('tests.index')
->with('data', $data);
}

Jquery json request and Kohana

I am trying to learn a little bit of jquery and more about the kohana framework. Ok so I wrote a simple test script to grab some entries from a database. The php works as in it returns the row in a json format, but I guess my jquery isn't working.
The json is suppose to return multiple rows so I want it to add all of those into the #chats div.
Here is my jquery code:
$(document).ready(function() {
$.getJSON('json/get_chat_entries/1',
function(data) {
$('#chats').append('<li>' + data.text + '</li>');
}
});
});
The get entries code is suppose to grab all the entries in the database matching the chat_id. Write now it seems to be only returning the first entry.
here is my get entries code:
function get_entries() {
$entries = $result = DB::select() - > from('chat_entries') - > where('chat_id', '=', $this - > chat_id) - > execute() - > current();
return $entries;
}
And this is the controller code:
public function action_get_chat_entries(){
$chat_id = $this->request->param('id');
$chat = new Model_Chat($chat_id);
echo json_encode($chat->get_entries());
}
Just remove ->current() from your get_entries() method.
Cleaned up a bit:
Model:
public function get_entries()
{
if (!$this->_loaded)
return array();
return DB::select()
->from('chat_entries')
->where('chat_id', '=', $this->chat_id)
->execute($this->_db);
}
Controller:
public function action_get_chat_entries()
{
$id = $this->request->param('id', FALSE);
$chat = new Model_Chat($id);
$this->request->headers['Content-Type'] = 'application/json';
$this->request->response = json_encode($chat->get_entries());
}
$results = DB::select(...)->from(...)->where(...)->execute();
echo json_encode(iterator_to_array($results));

Categories