How to update element of an array in MongoDB By PHP - php

I have a collection named 'question'. Its structure looks like this:
{
_id:
user_id:
answers:
[
{
answer_id:
answer_content:
}
,
{
...
}
,
...
]
}
Now I know the document's _id and answer_id of one answer,now I want to set the answer to
be a best_answer(add a field to the element) for example:
{
answer_id:
answer_content:
is_best:true
}
How can I do this?

You'll need to update the question document in the questions collection, one way is to $push the user info onto a answeredBy array field of some sort. Alternately you could create a separate answers collection and push answer documents containing the question id, uid, name, and answer.

$find_array = array('answers._id'=>$answer_id);
$this>collection>update($find_array,array('$set'=>array('answers.$.is_best' => true)));

Related

Push to a nested array in Mongo with Laravel

I have a structure of MongoDB that looks like this:
Object_id {
workflow {
tree_id {
other_ids {...}
other_ids {...}
other_ids {...}
subscribers {
subscriber_id {
email : value
}
}
}
}
}
}
It can be clearly seen on this screen:
My MongoDB structure
I want to add an another field, for example name : last_name, under the email : value. I tried it by using this code:
Model::where('_id', '5adde78993def907b71ce503')->push(array('workflow.5ace115a93def953d254b502.subscribers.5ad09c2993def90a2c59fa59' => ['test' => 'testvalue']));
However, this code doesn't work. It shows me an error saying:
The field 'workflow.5ace115a93def953d254b502.subscribers.5ad09c2993def90a2c59fa59' must be an array but is of type object in document {_id: ObjectId('5adde78993def907b71ce503')}
Updating with ['upsert' => true] also doesn't work, because this method removes my collection and adds data. How can I add something to this array?
Structure shown by you does not have any array in it. All are document or sub documents. you can not perform array operation on non array objects. To treat Subscriber_id as an array , it should be something like this
subscriber_id [{
email : value
}]
Model::where('_id', '5adde78993def907b71ce503')->push('workflow.5ace115a93def953d254b502.subscribers.5ad09c2993def90a2c59fa59' => ['test' => 'testvalue']);
please try this.

PDO fetch object key value as id and keep the id in the object

I have looked around alot with this problem. I want to get a array of my objects and the id should be the key value. I did this using the PDO::FETCH_UNIQUE.
It almost worked the way I want to. Problem here is that the ID will be removed from the object and will only show as the key value. But I want the key value as the id value AND KEEP the id attached to the object.
I tried this myself
$getUsers->fetchAll(\PDO::FETCH_UNIQUE|\PDO::FETCH_CLASS, User\Basic::class);
This does return the id, but the id is everywhere 0.
concept:
{
id: 3,
name: 'pietje'
},
{
id: 4,
name: 'pietje'
}
Then i want a array of object like this (I think I made a mistake here)
[3 => {
id: 3,
name: 'pietje'
},
4=> {
id: 4,
name: 'pietje'
}]
But like i sayed, the id in the object is always 0the way I did it, and i could not find anything on the internet about the way I want it. Yhea sure I can loop every user and add a id, but then I can just loop through every user and create a new array with the user id as key value.
Any one?
Just select your field twice,
SELECT id, table.* FROM table ...
PDO::FETCH_GROUP will allow you to group results; since you are grouping by id and should be unique you will get all rows as needed.
EDIT:
$sth = $pdo_dbh->prepare('SELECT id, name FROM users');
$sth->execute();
$result = $sth->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_ASSOC);
$result = array_map('reset', $result);
will return array like this.
Array
(
[2] => Array
(
[name] => Rob
)
[1] => Array
(
[name] => George
)
)
it helps move ID column as keys in result array, and only keeps desired columns in array values. I fail to notice you wish to fetch results as class object.
Unnecessary nesting removed with array_map.

Create a PHP array with the same key for multiple values [duplicate]

This question already has answers here:
PHP Associative Array Duplicate Keys
(6 answers)
Closed last month.
I'm posting a question already made here before and was not properly cleared for me.
I am trying to adapt a simple jquery code called “flexible calendar” and fill events trough our admin with meta keys.
The key is a date, the value a string. Here comes the problem. In order to use a jQuery calendar, I can dynamically create a JSON object like this:
var codropsEvents = {
'11-23-2016' : 'text',
'11-23-2016' : 'text two',
'11-20-2016' : 'some other text',
'11-19-2016' : 'Anything that is text'
};
But I need to get a JSON object as follows :
var codropsEvents = {
'11-23-2016' : 'text', 'text two',
'11-20-2016' : 'some other text',
'11-19-2016' : 'Anything that is text'
};
In this case, I need a code that causes them to recognize same date entries, and the nest correspontes values to the events of the same day, on the same row.
The thing is, PHP doesn't allow to use the same key in multiple rows : if I have multiple posts with the same date (a wp meta value), PHP only stores one in the array.
My calendar displays only one post per day.
How can I organize my PHP array in order to get the good format of the JSON object?
In fact, I don't need multiple rows with the same key. For every post with the same date, I need to create a row with a unique key (the date) and a unique value which will be a string containing all the posts titles.
You can do like this;
JSON
var codropsEvents = {
"11-23-2015":[
"text",
"some text",
"more text",
"bla bla"]
}
PHP
$codropsEvents = array('11-23-2015'=> array('text','some text','more text','bla bla'))
The Javascript object is not a valid object.
for (var properties in your_obj) {
// will not return dups
}
If they are different entries and you want to treat them as such, AND you have access to the JSON creation, make it like this:
[
{
"date" : "11-23-2015",
"content" : "text here"
},
{
"date" : "11-23-2015",
"content" : "text 2 here"
},
{
"date" : "11-23-2015",
"content" : "text 3 here"
}
]
then in you php use:
json_decode($jsonstring);
json_decode($string, true); // for nested array
see http://php.net/manual/en/function.json-decode.php
there was a very similar question:
https://stackoverflow.com/a/12561521/4792497

how to order a JSON response based on database relationship using eloquent

I'm quite new to Laravel and I'm trying to figure out how to properly work with Eloquent so far so good, but I'm stuck in something I want to do:
I have 3 tables in a database well 4 if you count the migrations one: food, food_group and portions which food_group and portion have the same structure which is and id as primary key and a name columns
the food ones have
| id(primary) | name | food_group_id (foreign key) | portion_id (foreign key |
all good because I have a nice formatted JSON with this in my route
Route::get('/read', function() {
$categories = App\FoodGroup::with('Foods')->get();
return Response::json(array('data' => $categories));
});
data: [
{
id: 1,
name: "Frutas",
foods: [
{
id: 18,
name: "Acelga",
cant_portion: 2
},
{
id: 19,
name: "Espinaca",
cant_portion: 2
},
]
}
]
and if I change the App\FoodGroup with App\Portion it gives me the same array but now ordered as the Foreign Key Portion
what I need is to first order with FoodGRoup and inside each item of the FFo_group one, now ordered by the second Foreign key which is Portion so I can have something like this
data: [
{
id: 1,
name: "Frutas",
portions:[
id: 18,
name: "Gr",
foods: [
{
id: 18,
name: "Acelga",
cant_portion: 2
},
{
id: 19,
name: "Espinaca",
cant_portion: 2
},
]
]
}
]
Your expected JSON shows foods as a child of portions. In order to do this, you need to setup this relationship.
On your Portion model, you need to setup the following relationship:
public function foods() {
return $this->hasMany(Food::class);
}
With this relationship setup, you can now get your data like this:
$categories = App\FoodGroup::with('portions.foods')->get();
This will load your food groups, then it will load the portions into the food groups, and then it will load the foods into the portions.
Edit
I may have slightly misread your question. I assumed you had a portions relationship defined on \App\FoodGroup. If not, you can add this like so:
FoodGroup:
public function portions() {
// the second parameter is the name of the pivot table.
// in this case, your foods table connects your portions and food groups.
return $this->belongsToMany(Portion::class, 'foods')->distinct();
}
Edit 2
This solution is a little hacky because it is treating the foods table as a pivot table, though it wasn't specifically designed for that. Because of this, there are multiple entries in the foods table that contain the same key pair values, and this is why you're getting duplicate related models.
If you throw a distinct() onto the relationship, this should take care of the issue, as it will eliminate the duplicates created from the inner join. The code above has been modified.
Based on the picture(ie your tables) you sent food_group does not have direct relationship with the portions so you can't chain food_group with portion like this
App\FoodGroup::with('portion.foods')
it should rather be (that is why you getting BadMethodCallException in Builder::portions())
App\FoodGroup::with('foods.portion')
because foodgroup has many foods and foods has many portion. so you can try something like this
App\FoodGroup::with(['foods.portion'=>function($q){
$q->orderBy('id')
}])->get();

Converting Array values into a temporary table

I have two columns member id and author id
Member A gives a list of author ids in a array format. I need to run a check against my database to see if these author ids are already there in my database, if they are present take the member ids of these authors and link them to the member id of A.
What is the efficient method to do this? Is it advisable to store the author ids to a temporary table and run the check and fetch it. The number of author ids in the array runs to few thousands.
Can you share some sample codes please? I am currently using PHP and MySql.
Update - I get an array of JSON objects with author id and name as follows:
{
"name": "Harold Robinson",
"id": "912065"
},
{
"name": "Gilbert Patten",
"id": "1212140"
},
{
"name": "Leo Tolstoy",
"id": "6012954"
}
I already have a table called Authors against which these data needs to be compared and if the ids match the user id assigned to the author has to be linked to User A.
Table Authors
User id: 109876
id: 912065
FYI, you won't get a useful answer if your question is not clear and with enough detail. This is a though one because the question is not very clear but I will attempt to the best of my understanding of the question. We can then tweak the answer as you clarify the question further.
//Not sure how you are collecting the ids into an array so I will just create one here for show.
$member_authors = array (1, 2, 3);
foreach ($member_authors as $authorID) {
$query = "SELECT author_id FROM authors WHERE author_id ='" . $authorID . "'";
$result = mysql_query($query);
if (mysql_affected_rows() > 0) { //If a value was returned then the author does exist in the database.
//Do whatever you want with the authorID.
}
}
I hope this helps.

Categories