Adding a Value to Collection Items - laravel-5.1

I want to load data from many files. Each file is named with a date and I need to inject this date to each of the fetched Entries of my file.
I know I could do this with an foreach - loop before inserting the data into the collection, but I think there should be a better solution.
Content of one file
[{"price":"95,34","isin":"FR0000120073"},{"price":"113,475","isin":"CA13645T1003"}]
The Code I use to move the data into a collection.
$collection= collect(json_decode(File::get($file)));
I tried for example the "map" method, however I don't know how to pass an additional variable to the anonymous function.
The content of my collection should look like this:
[{"price":"95,34","isin":"FR0000120073","date":"2016-06-23"},{"price":"113,475","isin":"CA13645T1003","date":"2016-06-23"}]
Is there any simple solution using the collections or do I have to use a foreach-loop?

May be this will help
$collection = collect(json_decode(File::get($file)));
$collection = $collection->each(function ($item, $key) {
//First iteration of $item will be {"price":"95,34","isin":"FR0000120073"}
$item->date = "2016-06-23"; //Insert key, value pair to the collection
});

Related

Query inside unique document inside collection in Firestore

I'm trying to query for an id inside an array of a document, but I just found a way that I query inside the whole collection, and I think this is not the most optimized way to do this.
This is what I'm thinking about:
theColletionReference.document("theDocumentId").whereField("fieldName", arrayContains: ["theIdImLookingFor"]).getDocument{
//the code remaining
}
I know that the code above is wrong, but that is the idea I'm trying to implement!
This is my database:
If you want to do anything at all with a single document, simply get() it and examine the contents of the document sbapshot to see if it contains what you want. There is no need for a full query just to see if a document contains some value.

Append element to Firebase Array

How I could append an element to an array like that:
Using this code I'm overriding the old data:
let toUpdate = [book.id]
self.refUsers.child(localUser.key!).child("booksPurchased").setValue(toUpdate, withCompletionBlock: { (error, _) in
You could use this method: firebase.firestore.FieldValue.arrayUnion()
Example with angularfire2:
this.afs.collection('collection').doc(id).update( {
array: firebase.firestore.FieldValue.arrayUnion( 'newItem' )
});
For more information: https://firebase.google.com/docs/reference/js/firebase.firestore.FieldValue#arrayunion
In this case, you will have to read the existing data, then write it back with the new value added. Arrays like this are not always the best way to store lists of data if you want to perform a lot of append operations. For that, you're better off pushing data into a location using childByAutoId.
Reading and writing lists
Append to a list of data
Use the childByAutoId method to append data to a list in multiuser applications. The childByAutoId method generates a unique key every time a new child is added to the specified Firebase reference. By using these auto-generated keys for each new element in the list, several clients can add children to the same location at the same time without write conflicts. The unique key generated by childByAutoId is based on a timestamp, so list items are automatically ordered chronologically.
You can use the reference to the new data returned by the childByAutoId method to get the value of the child's auto-generated key or set data for the child. Calling getKey on a childByAutoId reference returns the auto-generated key.
You can use these auto-generated keys to simplify flattening your data structure. For more information, see the data fan-out example.
-https://firebase.google.com/docs/database/ios/lists-of-data
You could set the values of the keys in the array to true, and then set the value directly in an update.
So if 'newId' is the new item to add, maybe something like:
const update = {
[`/users/${localUser.key}/booksPurchased/${newId}`]: true]
}
firebase.db.ref().update(update);
Firebase docs example of an update:
https://firebase.google.com/docs/database/web/read-and-write

Phalcon Save: Can I update only specified columns if update?

I have a table with this columns:
param_id
val_value
val_flag
date_value
tmp_value
tmp_flag
And I have an array of elements, I always have param_id and date_value, but sometimes i have val columns and other times I have tmp columns.
I use $data->save() because sometimes I need to create a new register in db and other times I need to update the register with param_id and date_value.
The question is: Is there any way to do an insert/update but when is an update, only update tmp columns or val columns? I think a find First is my only option, but maybe there is another way.
Thank you.
[EDIT]
I'm trying with the whitelist but it does not work. Let me explain how the method works: I get a request to a web service, process the xml and generate an array of elements with the information collected, after processing these elements I have an array of elements of the class appropriate to save, but these may be new or existing and may contain tmp or val values, I have tried with this but I still change the values to null.
if ($medida->tipo == 'temporal'){
$whiteList = array('val_value','val_flag');
}else if ($medida->tipo == 'validado'){
$whiteList = array('tmp_value','tmp_flag');
}
$dato->save(null, $whitelist);
I do not have data of the post, I use null instead, I have also tried to use an array with the manual assignment of the data obtaining the same result.
Here are two options that can help you:
1) Use 'whitelist' for the save() method.
$obj->save($this->request->getPost(), ['tmp_1', 'tmp_2']);
More info in the documentation.
2) Use the 'Event Manager'.
The methods beforeCreate() and beforeUpdate() will be useful so you can decide which fields to use.
More info in the documentation.
Also if you really want phalcon phql to update only columns which changed you need to enable dynamic update.

How can I match with the persistent_object_identifier?

Is there a way to use the query interface and limit the repository query by the persistent object identifier? Like ...
// $addTaskIds is an array with identifiers as strings
$query = $this->createQuery();
$query->matching(
$query->logicalOr(
$query->like('title', '%'.$searchstring.'%'),
$query->like('description', '%'.$searchstring.'%'),
$query->in('persistent_object_identifier', $addTaskIds)
)
);
return $query->execute();
I've tried the code above and it doesn't work. Did I forgot something? Does the query builder offer that anyway? Do I have to switch on a yaml setting?
The idea was good. But the table row persistent_object_identifier doesn't belong to the object itself. You can however use Persistence_Object_Identifier.
For that you need the identifiers as strings not as whole objects. And make sure that the second parameter of 'query in' is an array not a single string.

Dynamic Tag Management - Storing

We're in the process of moving to DTM implementation. We have several variables that are being defined on page. I understand I can make these variables available in DTM through data elements. Can I simply set up a data elem
So set data elements
%prop1% = s.prop1
%prop2% = s.prop2
etc
And then under global rules set
s.prop1 = %s.prop1%
s.prop2 = %s.prop2%
etc
for every single evar, sprop, event, product so they populate whenever they are set on a particular page. Good idea or terrible idea? It seems like a pretty bulky approach which raises some alarm bells. Another option would be to write something that pushes everything to the datalayer, but that seems like essentially the same approach with a redundant step when they can be grabbed directly.
Basically I want DTM to access any and all variables that are currently being set with on-page code, and my understanding is that in order to do that they must be stored in a data element first. Does anyone have any insight into this?
I use this spec for setting up data layers: Data Layer Standard
We create data elements for each key that we use from the standard data layer. For example, page name is stored here
digitalData.page.pageInfo.pageName
We create a data element and standardize the names to this format "page.pageInfo.pageName"
Within each variable field, you access it with the %page.pageInfo.pageName% notation. Also, within javascript of rule tags, you can use this:
_satellite.getVar('page.pageInfo.pageName')
It's a bit unwieldy at times but it allows you to separate the development of the data layer and tag manager tags completely.
One thing to note, make sure your data layer is complete and loaded before you call the satellite library.
If you are moving from a legacy s_code implementation to DTM, it is a good best practice to remove all existing "on page" code (including the reference to the s_code file) and create a "data layer" that contains the data from the eVars and props on the page. Then DTM can reference the object on the page and you can create data elements that map to variables.
Here's an example of a data layer:
<script type="text/javascript">
DDO = {} // Data Layer Object Created
DDO.specVersion = "1.0";
DDO.pageData = {
"pageName":"My Page Name",
"pageSiteSection":"Home",
"pageType":"Section Front",
"pageHier":"DTM Test|Home|Section Front"
},
DDO.siteData = {
"siteCountry":"us",
"siteRegion":"unknown",
"siteLanguage":"en",
"siteFormat":"Desktop"
}
</script>
The next step would be to create data elements that directly reference the values in the object. For example, if I wanted to create a data element that mapped to the page name element in my data layer I would do the following in DTM:
Create a new data element called "pageName"
Select the type as "JS Object"
In the path field I will reference the path to the page name in my data layer example above - DDO.pageData.pageName
Save the data element
Now this data element can be referenced in any variable field within any rule by simply typing a '%'. DTM will find any existing data elements and you can select them.
I also wrote about a simple script you can add to your implementation to help with your data layer validation.Validate your DTM Data Layer with this simple script
Hope this helps.

Resources