How can we update student selections? - php

I have a db with two collections. Students collection has a field named "student_bookselections" that keeps the ids of books. Content of this field will often be changed or updated.
How can we add or delete ids to student_bookselections?
Is this a decent way to relate the collections?
students collection
array(
"student_id" => 4,
"student_fullname" => $studentfullname,
"student_bookselections" => 'id1, id34, id788 ... ... id4'
)
books collection
array(
"book_id" => 4354,
"book_title" => $title,
"book_author" => $author,
)

You would be better off having a third table to link students to books, your current implementation is not normalized.
Users(
"student_id" => 4,
"student_fullname" => $studentfullname
)
Books(
"book_id" => 4,
"book_title" => $title,
"book_author" => $author
)
Selections(
"selection_id" => 4,
"student_id" => $studentid,
"book_id" => $bookid
)
You can then define relationships with foreign keys to link the tables, and more importantly each row is relating to one piece of information. If you wanted to know all book selections for a certain student
mysql_query("SELECT * FROM Selections WHERE student_id = $student_id");
Hope that helps!

To update
<?php
$mongo = new Mongo();
$db = $mongo->selectDB("Your_Database");
$student = $db->students;
$update = array("$set" => array("student_bookselections" => "your ids"));
$where = array("student_id" => 4);
$student->update($where,$update);
?>
To insert
<?php
$mongo = new Mongo();
$db = $mongo->selectDB("Your_Database");
$student = $db->students;
$insert = array("student_fullname" => "Stefan", "student_bookselections" => "your ids" );
$student->insert($insert);
?>
To Remove
<?php
$mongo = new Mongo();
$db = $mongo->selectDB("Your_Database");
$student = $db->students;
$student->remove(array("ID" => 4));
?>
Relation
(See post from Crhis)
Users(
"student_id" => 4,
"student_fullname" => $studentfullname
)
Books(
"book_id" => 4,
"book_title" => $title,
"book_author" => $author
)
Selections(
"selection_id" => 4,
"student_id" => $studentid,
"book_id" => $bookid
)
Select with this relation
<?php
$mongo = new Mongo();
$db = $mongo->selectDB("Your_Database");
$selection = $db->selections;
$res = $student->find(array("student_id" => $student_id));
?>

Related

Codeigniter, mysql, select_max and add 1 before inserting another record

When I insert a new record into a database table, I need to take an existing previous value of a column called el_order, add +1, and use that new el_order+1 to insert the new record with that value in the column.
I can't use autoincrement because I need to do some things with that column (reorder, move, etc) and have to use it as an integer.
Table
ID name el_order
1 1 1
21 bla 2
2 2 3
--NEW-- --NEW-- 3+1 (NEW)
I add a new record, and need to insert it with 3+1 in it's el_order column...
I have tried this, but no luck:
$this->db->select_max('el_order');
$res = $this->db->get('elem_diccio');
$eldi_key = url_title($this->input->post('id'), 'underscore', TRUE);
$el_order = $res+1;
$datos = array(
'ID' => $id,
'el_order' => $el_order,
'name' => $this->input->post('name'),
);
$this->db->insert('elem_diccio', $datos);
Just like this
$this->db->select_max('el_order');
$res = $this->db->get('elem_diccio')->row()->el_order;
$eldi_key = url_title($this->input->post('id'), 'underscore', TRUE);
$el_order = $res+1;
$datos = array(
'ID' => $id,
'el_order' => $el_order,
'name' => $this->input->post('name'),
);
$this->db->insert('elem_diccio', $datos);
$res is a CI_DB_mysqli_result Object. To get the column, you need
$this->db->select_max('el_order');
$res = $this->db->get('elem_diccio')->row();
$el_order = $res->el_order+1;
$datos = array(
'ID' => $id,
'el_order' => $el_order,
'name' => $this->input->post('name'),
);

Laravel : Update if exists, If not delete | Relational data

I am updating/deleting some form data in database :
The relation is : One to Many: UserService => UserServiceVaccine
I am trying to update the table data if the form have that data, Otherwise remove if form data have not the data :
Current code :
foreach ($request->dog_vaccine_required as $key => $vaccine) {
$serviceVaccination = \App\UserServiceVaccination::updateOrCreate([
'user_service_id' => $id,
'vaccine_id' => $vaccine
],[
'specie' => 'Dog',
'user_service_id' => $id,
'vaccine_id' => $vaccine,
'duration_6' => $request->dog_duration_6[$key],
'duration_12' => $request->dog_duration_12[$key],
'duration_36' => $request->dog_duration_36[$key]
]);
}
It gives me offset exception. if i remove a checkbox.
What should be done.
Do you can try this ?
foreach ($request->dog_vaccine_required as $key => $vaccine) {
$shouldUpdate=isset($request->dog_duration_6[$key])&&
isset($request->dog_duration_12[$key])&&
isset($request->dog_duration_36[$key]);
if ($shouldUpdate){
$serviceVaccination = \App\UserServiceVaccination::updateOrCreate([
'user_service_id' => $id,
'vaccine_id' => $vaccine
],[
'specie' => 'Dog',
'user_service_id' => $id,
'vaccine_id' => $vaccine,
'duration_6' => $request->dog_duration_6[$key],
'duration_12' => $request->dog_duration_12[$key],
'duration_36' => $request->dog_duration_36[$key]
]);
}else{
// Delete
}
}
I think that's a "many to many" relationship between user_service table and vaccine table.
Based on the docs here https://laravel.com/docs/5.6/eloquent-relationships#many-to-many
$serviceVaccinationArray = [];
foreach ($request->dog_vaccine_required as $key => $vaccine) {
$serviceVaccinationArray[$vaccine] = [
'vaccine_id' => $vaccine,
'specie' => 'Dog',
'duration_6' => $request->dog_duration_6[$key],
'duration_12' => $request->dog_duration_12[$key],
'duration_36' => $request->dog_duration_36[$key]
]
}
$userService = UserService::find($id);
$userService->vaccine()->sync($serviceVaccinationArray);
The sync method accepts an array of IDs to place on the intermediate table. Any IDs that are not in the given array will be removed from the intermediate table.

Salesforce PHP SOAP API. How to populate a lookup field?

I have a custom object called "Chapter_Detail__c". I am creating a LEAD, and a lead has a look up field(link_id__c) which is mapped with "Chapter_Detail__c".
How can i populate this look up field while creating the Lead.
$sObject = new SObject();
$fieldsToInsert = array (
'FirstName' => $name_rsform,
'LastName' => $username_rsform,
'Company' => 'TestSession',
'Full_Name__c' => $name_rsform,
'Chapter_Name__c' => $chapter_name_rsform,
'Role__c' => $role_rsform_label,
'Email__c' => $email_rsform,
'Branch_of_service__c' => $bos_f,
// 'link_id__c' => $chapter_id_rsform, - DOES NOT WORK THIS WAY ITS A LOOKUP RELATIONSHIP WITH OBJECT "Chapter_Detail__c"
);
$sObject->fields = $fieldsToInsert;
$sObject->type = 'Lead';
//echo "**** Creating the following:\r\n";
$createResponse = $mySforceConnection->create(array($sObject));
//print_r($createResponse);
echo 'Get ID after create';
$ids = array();
foreach ($createResponse as $createResult) {
print_r($createResult);
array_push($ids, $createResult->id);
}
$idRecieved = $ids[0];
Any kind of help will be appreciated. Thanks.

Group results after join?

So, I have three tables. Movies, movies_genres and genres. I want to get a movie by its Id, and also join its genres in the result. I managed to join the results, but it doesn't display as i want it to. I'm not sure if what I'm asking is possible.
This is my query:
SELECT `movies`.*, GROUP_CONCAT(genres.id) AS genre_id, GROUP_CONCAT(genres.name) AS genre_name
FROM (`movies`)
INNER JOIN `movies_genres`
ON `movies_genres`.`movie_id` = `movies`.`id`
INNER JOIN `genres`
ON `genres`.`id` = `movies_genres`.`genre_id` WHERE `movies`.`id` = 19908
GROUP BY `movies`.`id`
The query was generated by Codeigniters Active Record class, here is the Codeigniter code if that helps:
$this->db->select('movies.*, GROUP_CONCAT(genres.id) AS genre_id, GROUP_CONCAT(genres.name) AS genre_name');
$this->db->from('movies');
$this->db->where('movies.id', $movie_id);
$this->db->join('movies_genres', 'movies_genres.movie_id = movies.id', 'inner');
$this->db->join('genres', 'genres.id = movies_genres.genre_id', 'inner');
$this->db->group_by('movies.id');
Here is the result i'm currently getting:
Array
(
[id] => 19908
[movie_title] => Zombieland
[overview] => An easily spooked guy...
[genre_id] => 28,12,35,27
[genre_name] => Action,Adventure,Comedy,Horror
)
And this is what I want:
Array
(
[id] => 19908
[movie_title] => Zombieland
[overview] => An easily spooked guy...
[genres] => array(
0 => array(
'id' => 28,
'name' => Action
),
1 => array(
'id' => 12,
'name' => Adventure
),
1 => array(
'id' => 35,
'name' => Comedy
),
1 => array(
'id' => 27,
'name' => Horror
)
)
)
Is this possible, and if so, how?
The query you listed will have n rows (where n = # of movies) whereas the query it seems you want will have many more rows (# of movie_genre's entries). You're probably better off leaving that query as it is, and doing some post processing.
Consider:
After you get it, just run your result (e.g. $result) array through something like:
foreach($result as &$row)
{
// Split over commas
$gi_elements = explode(',', $row['genre_id']);
$gn_elements = explode(',', $row['genre_name']);
// Build genre
$row['genre'] = array();
for($i=0; $i<count($gi_elements); $i++)
{
$row['genre'][] = array('id' => $gi_elements[$i], 'name' => $gn_elements[$i]);
}
// Cleanup
unset($row['genre_id']);
unset($row['genre_name']);
}
Afterwards, $results will look exactly as you wish without extra database work.
EDIT: Fixed some typos.

How to get all table columns without defining them in query?

I have two tables, User and Company. I have joining them like this:
$table = $this->getDbTable();
$select = $table->select();
$select->setIntegrityCheck( false );
$select->from( array('User'), array( 'id' => 'id',
'name' => 'User.name',
'gender' => 'User.gender',
'Company_id' => 'User.Company_id'
));
$select->join( 'Company', 'Company.id = User.Company_id',
array( 'Company_name' => 'Company.name' ,
'Company_address' => 'Company.address'
));
$rows = $table->fetchAll( $select );
It is working and giving me accurate result. Problem is that I have to mentions column names in above codes. I want to get all columns without mentioning them in above piece of code.
For example I want something like this that get all columns(But it is not providing all column values):
$table = $this->getDbTable();
$select = $table->select();
$select->setIntegrityCheck( false );
$select->from( array('User') );
$select->join( 'Company', 'Company.id = User.Company_id' );
$rows = $table->fetchAll( $select );
Thanks
Leaving away the second parameter to the from call should work: http://framework.zend.com/manual/en/zend.db.select.html#zend.db.select.building.columns

Categories