Get distinct dates from json array joomla - joomla

My component saves json array in database :
so i want to get distinct dates from all the fields.
database field contains values like this :
a:3:{i:0;s:16:"2013-02-24 00:00";i:1;s:16:"2013-02-23 00:00";i:2;s:16:"2013-02-22 00:00";}

What you have there is serialized data, not json encoded. I don't believe there is a way to grab just the dates out of the database using a mysql query (hence most people recommending that you don't store data in a serialized or even a json form).
You would want to grab the data from the database maybe like so (with the $query variable being the query you need to get data from the database. Since I have no idea what your database looks like, I'm not going to write the query)
$rows = JFactory::getDbo()->setQuery($query)->loadObjectList();
foreach ($rows as $row) {
$dates = unserialize($row->date_column);
// do something with the $dates variable, which is now an array of the three dates.
}

Related

How to get distinct dates from a datetime field

I have this field valid_upto which is a datetime, so if I do:
$dates = Game::where('week', $this->week)
->distinct('valid_upto')
->pluck('valid_upto');
It returns an array like:
["2022-09-08 19:20:00",
"2022-09-11 12:00:00",
"2022-09-11 15:25:00",
"2022-09-11 19:20:00",
"2022-09-12 19:15:00",]
But I only want the date part, like:
["2022-09-08",
"2022-09-11",
"2022-09-12",]
is there a way to do it directly in Laravel's ORM? I don't want to use a rawSelect or similar, I know I could apply DATE('valid_upto') as d in mySQL and Postgres, but I really like to use "general" approaches.
This would work:
foreach ($dates as $i => $d) $dates[$i]=explode(" ", $dates[$i])[0]
$dates = $dates->unique()
But I think its an horrible solution
Something I would like to do, instead of using that foreach, applying a lambda (like in Python) to the Collection and then use the distinct. But I don't know if Laravel has lambdas.
In Laravel you can use Mutators and Casters to determine how certain columns are formatted when you access them. Laravel applies the casting when the model is serialized to json or to an array. So your query could become:
$dates = Game::where('week', $this->week)
->distinct('valid_upto')
->get('valid_upto')
->toArray();
And if you apply a caster on your Game model like so:
protected $casts = [
'valid_upto' => 'datetime:Y-m-d',
];
that should get you a collection of the dates you want in the format you want.

Laravel Collection Filter breaking serialization format

I have a serialized String like this
$string = '[{"name":"FOO"},{"name":""},{"name":"BAR"}]';
I am trying to process it via Laravel Collection's filter method and eliminate items without a defined "name" property.
$collection = collect(\json_decode($string));
$collection = $collection->filter(function($v){
return !empty($v->name);
});
$string = \json_encode($collection->toArray());
dd($string);
Normally I am expecting something like this:
[{"name":"FOO"},{"name":"BAR"}]
But I'm getting something like this:
{"0":{"name":"FOO"},"2":{"name":"BAR"}}
Funny thing is, if I skip the filtering process or return true every time, I keep getting the string in the desired format. Removing the toArray() call has the same result. I don't want to keep the numeric indices as associative object keys.
Why this anomaly? And what should I do to get the serialized data in desired format?
In PHP arrays the index key must be unique.
In your case you have the key 'name' and collection automatically assigns the index key to all items in the collection.
To overcome that problem just call
$string = \json_encode($collection->values());

Laravel Array to string conversion error while updating database

I want to update a totcosty field in the User table but it is throwing this error everytime and it is not updating the field
this is the function for execution:
public static function cost(){
$user = User::find($user_id);
$total = Helper::totcost();
// dd($tot_amt);
$user->totcosty = $total;
$user->save();
}
array to string means you are sending an array to the database but db will not accept it you have to explode() the array before sending it to db...
Hope it will help!
If you really want to store an array in some table field, then better declare it as a JSON field. For this, your DB should have support for JSON type columns.
See here how to do this.
Once this is done, you can save arrays in that column, you can assign an array value to the model property and laravel will convert it to JSON while saving and also it will be converted to array while retrieving.

Laravel 5.1 eloquent query orderby external data and paginated

I'm trying to get data from an Eloquent query (that works), then order the data, then paginate the data.
I had the code ordering by date, then paginating, but now I want to order by facebook API obtained data (I get the data correctly).
The thing is I don't know what I should do first (paginate or ordering):
If I paginate first, I don't know how to order the data since the object is LengthAwarePaginator and doesn't have any orderBy method.
If I order first, I get a collection object and can't use ->paginate($perPage) to do the pagination.
This is the code:
$posts = Post::with('User')->
where('created_at', '<', new \DateTime)->
paginate($perPage);
$counter = 0;
foreach ($posts as $post) {
$url = 'http://myweb.com/' . $post['id'];
$fb_stuff = json_decode(file_get_contents('https://api.facebook.com/method/links.getStats?urls=' . $url . '&format=json'), true);
$posts[$counter]['share_count'] = $fb_stuff[0]['share_count'];
$counter++;
}
If you need to sort by some value that is not stored in the database then the only option is to fetch all records from the database, fetch the sorting data from external source (Facebook API), sort it by user defined function (see http://php.net/manual/en/function.usort.php) and then paginate.
Once you have your data sorted you can easily get the paginated version by creating a Paginator object:
$paginator = new \Illuminate\Pagination\Paginator($posts, $perPage, $currentPage);
Anyway, this solution will be quite heavy as you'll need to fetch data from Facebook API every time you want a sorted list of posts. I doubt you need real time data so I suggest to store share_count in your posts table and refresh it on regular basis, e.g. by running a scheduled laravel command.

Doctrine toarray does not convert relations

I followed doctrine documnetation to get started. Here is the documentation.
My code is
$User = Doctrine_Core::getTable("User")->find(1);
when I access relations by $User->Phonenumbers, it works. When I convert User object to array by using toArray() method, it does not convert relations to array. It simply display $User data.
Am I missing something?
By using the find method you've only retrieved the User data which is why the return of toArray is limited to that data. You need to specify the additional data to load, and the best place to do this is usually in the original query. From the example you linked to, add the select portion:
$q = Doctrine_Query::create()
->select('u.*, e.*, p.*') // Example only, select what you need, not *
->from('User u')
->leftJoin('u.Email e')
->leftJoin('u.Phonenumbers p')
->where('u.id = ?', 1);
Then when toArray'ing the results from that, you should see the associated email and phonenumber data as well.
I also noticed an anomaly with this where if you call the relationship first then call the ToArray, the relationship somehow gets included. what i mean is that, taking your own eg,
$User = Doctrine_Core::getTable("User")->find(1);
$num= $User->Phonenumbers->office; // assumed a field 'office' in your phone num table
$userArray = $user->toArray(true);
In the above case, $userArray somehow contains the whole relationship. if we remove the $num assignment it doesn't.
am guessing this is due to doctrine only fetching the one record first, and it's only when you try to access foreign key values that it fetches the other related tables

Resources