CakePhp does update instead of insert new data - php

i started using cakephp, but now i encountered a problem which i am not able to solve.
I have got the following model relations which are relevant:
Exercise hasMany Points
Student hasMany Points,
now i want to check in the studentsController if for every exercise there is a Point data set, and iff not insert a new one.
When starting with no Point datasets, the function adds a new Point dataset for the first exercise correct, but after this it only updates the erxercise_id of this dataset, instead of creating new ones.
The controller function looks like this:
public function correct($id = null) {
$this->Student->id = $id;
$this->Student->recursive = 2;
if ($this->request->is('get')) {
$data = $this->Student->Exam->Exercise->find('all');
foreach($data as $exercise)
{
$exerciseID = $exercise['Exercise']['id'];
$this->Student->Point->recursive = 0;
$foundPoints = $this->Student->Point->find('all', array('conditions' => array('exercise_id' => $exerciseID)));
if($foundPoints == null)
{
$emptyPoints = array ('Point' => array(
'exercise_id' => $exerciseID,
'student_id' => $id
)
);
$this->Student->Point->save($emptyPoints);
}
else{
}
}
}
else //POST
{
}
}

if you have to insert a data you to use create() method like this:
This is only an example, with this line you create every time a new record into your database
and save data
$this->Student->Point->create();
$this->Student->Point->save($emptyPoints);

$this->Student->Point->id = '';
$this->Student->Point->save($emptyPoints);
or
$this->Student->Point->saveAll($emptyPoints);

Related

Laravel 5.5 - Unable to update object

It's been a while since I've used Laravel and I'm pulling my hair out over the below issue, seems to be relatively straight forward and probably 100% obvious.
I'm adding some new fields to an existing view, I've created a new model, added the relations and added the fields. I can confirm that I'm able to view the data on the View successfully, I can take the data from the view successfully and insert a new record on the target table.
The problem I'm having is I'm unable to update an existing record, I can retrieve the record by ID, but I can't use the object selector ($object->data) on it, I've added the function and the comments below:
//Create the license
$license = License::where('id', $venue->license_id)->get();
if(empty($license->id))
{
Log::notice("Nothing to show");
} else {
//I have added this in as a sanity check, I've been able to
//perform Log::notice($license); successfully but the below doesn't work?
Log::notice($license->id);
Log::notice($license->license_name);
}
//This works, I am able to create a new License if there is no ID set.
$license_class_id = $request->get('license_class_id');
$license_type_id = $request->get('license_type_id');
$liquor_license_no = $request->get('liquor_license_no');
$site_reference_no = $request->get('site_reference_no');
$holder_name = $request->get('holder_name');
$license_name = $request->get('license_name');
$trading_name = $request->get('trading_name');
//This works
if( !$license || !$license->exists ) {
$license = new License;
}
//This is to update the object but it doesn't seem to happen.
$license->license_class_id = $license_class_id;
$license->license_type_id = $license_type_id;
$license->liquor_license_no = $liquor_license_no;
$license->site_reference_no = $site_reference_no;
$license->holder_name = $holder_name;
$license->license_name = $license_name;
$license->trading_name = $trading_name;
if ( ! $license->save() ) {
return $license->errors();
}
if(!empty($license->id))
{
$venue->license_id = $license->id;
}
if ( ! $venue->save() ) {
return $venue->errors();
}
use update() method for update not save(). save() is used at the insert time
$license->update();
And fetch record as single collection. If id is not primary key then by below way
//Create the license
$license = License::where('id', $venue->license_id)->first();
And if id is primary key then you directly get by
$license = License::find($venue->license_id);
You can use updateOrCreate method here too.
By this code,
//Create the license
$license = License::where('id', $venue->license_id)->first();
if(empty($license))
{
Log::notice("Nothing to show");
} else {
//I have added this in as a sanity check, I've been able to
//perform Log::notice($license); successfully but the below doesn't work?
Log::notice($license->id);
Log::notice($license->license_name);
}
//This works, I am able to create a new License if there is no ID set.
$license_class_id = $request->get('license_class_id');
$license_type_id = $request->get('license_type_id');
$liquor_license_no = $request->get('liquor_license_no');
$site_reference_no = $request->get('site_reference_no');
$holder_name = $request->get('holder_name');
$license_name = $request->get('license_name');
$trading_name = $request->get('trading_name');
License::updateOrCreate([
'license_class_id' => $license_class_id ,
'license_type_id' => $license_type_id,
'license_type_id' => $license_type_id,
'license_type_id' => $license_type_id,
'holder_name' => $holder_name,
'license_name' => $license_name,
'trading_name' => $trading_name
]);
For more information check this link.
If you will use this method, You do not need to check if a record exists or not. That is the advantage.

sync an array with pivot attributes in Laravel

I'm building a small application on Laravel 5.4and facing a little difficulty in syncing the pivot table in many to many relationship, I went through this link and not understood properly,
I'm having a pivot table which is mandatory field(I mean it will have field). I'm having a relationship something like this:
class Interaction extends Model
{
public function clientsAssociation()
{
return $this->belongsToMany('App\Contact', 'contact_client_interaction', 'interaction_id', 'contact_id')->withPivot('company_id')->withTimestamps();
}
}
I'm getting an array with set of values related to sync to these models. I'm confused how to place pivot data and while updating:
foreach ($data['clientParticipants'] as $clientParticipant)
{
if(array_key_exists('company_id', $clientParticipant))
{
$contact[] = Contact::find(json_encode($clientParticipant['value']));
$pivotData = ['company_id' => $clientParticipant['company_id']];
}
else
{
$contact[] = Contact::find(json_encode($clientParticipant['value']));
$pivotData = ['company_id' => Contact::find(json_encode($clientParticipant['value']))->company()->withPivot('created_at')->orderBy('pivot_created_at', 'desc')->first()->id])];
}
$interaction->clientsAssociation()->sync($contact);
}
Guide me to achieve this. Thanks
Well I did something like this:
foreach ($data['clientParticipants'] as $clientParticipant)
{
if(array_key_exists('company_id', $clientParticipant))
{
$pivotData = ['company_id' => $clientParticipant['company_id']];
$syncData = Contact::find(json_encode($clientParticipant['value']))->id;
$contact[$syncData] = $pivotData;
}
else
{
$value = Contact::find(json_encode($clientParticipant['value']));
$syncData = $value->id;
$pivotData = ['company_id' => $value->company()->withPivot('created_at')->orderBy('pivot_created_at', 'desc')->first()->id];
$contact[$syncData] = $pivotData;
}
}
$interaction->clientsAssociation()->sync($contact);
And it works. So basically idea is to push an array with key of pivot elements and it will execute properly.

how to insert array data in single column in mysql using codeigniter

I'm trying to insert array data into database using codeigniter. when I print that values using print_r() fun.
It shows correct result, but when I click on save button it inserts blank values in table.
I just want to store multiple medicine names in prescription table for particular prescription_id i am trying to insert data using insert_batch function but it saves blank records
this is my model code:
public function add_prescription($data) {
$data['medicine_name'] = $data['medicine_nm[]'];
print_r($data['medicine_name']);
$this->db->insert_batch('pre',$data);
return $this->db->insert_id($pre_id);
}
controller code--
public function prescription($patient_id = NULL, $app_date = NULL, $hour = NULL , $min = NULL) {
//Check if user has logged in
if (!$this->session->userdata('user_name') || $this->session->userdata('user_name') == '') {
redirect('login/index/');
} else {
if ($this->form_validation->run() === FALSE) {
$data['medicine_nm[]']=$this->input->post('medicine_nm[]');
$this->patient_model->add_prescription($data);
}
}
}
You need to json_encode that array and then insert it into the database like
$data = json_encode($array);
$this->db->insert('column_name',$data);
And while fetching you need to decode it
$data = json_decode($column_result);
Hope this helps you.
try this
public function add_prescription($name) {
$data = array(
'medicine_name' => $name
);
$query = $this->db->insert('table_name',$data);
return $query->result_array();
}
Hope this will help you

Symfony2 Generate SQL logs for specific functions in my controller

I have some functions which are used to insert and update database tables in my Symfony2 project. For those functions I want to generate a verbose SQL log for all insert and update queries which are being executed with their result.
I have tried to do it manually but I am unable to get the SQL queries from the object that is persist and Flushed.
Here is my controller function:
private function pushChapterToCdpCodes($testObjectEntity, $testReleaseId) {
$chapterTitle = $testObjectEntity->getTitle();
$chapterNumber = $testObjectEntity->getNumber();
$chapterOriginalId = $testObjectEntity->getOriginalId();
// update chapter table
if ($chapterOriginalId) {
$chapter = $this->chapterRepository->findOneBy(array('id' => $chapterOriginalId));
} else {
$bookTitle = $testObjectEntity->getBook()->getTitle();
$bookObject = $this->bookRepository->findOneBy(array('title' => $bookTitle));
$bookId = $bookObject->getId();
$bookPart = $testObjectEntity->getBookPart();
$chapter = new \ICC\BookBundle\Entity\Chapter();
if ($bookPart) {
$bookPartOriginalNumber = $testObjectEntity->getBookPart()->getNumber();
$bookPartOriginalTitle = $testObjectEntity->getBookPart()->getTitle();
$originalBookPart = $this->bookPartRepository->findOneBy(array('number' => $bookPartOriginalNumber, 'title' => $bookPartOriginalTitle));
$chapter->setBookPart($originalBookPart);
} else {
$chapter->setBook($this->bookRepository->findOneBy(array('id' => $bookId)));
}
}
$chapter->setTitle($chapterTitle);
$chapter->setNumber($chapterNumber);
$chapter->setErrataReleaseId($testReleaseId);
$this->cdpCodesEm->persist($chapter);
$this->cdpCodesEm->flush();
}
I need the SQL log for the above $this->cdpCodesEm->persist($chapter); result.
Please help me what is the right way to do this.

How to submit data to multiple tables in the same form

I have 2 tables: listings and listings_specifications
Listings table
id
type
status
location
specifications_id
Listings_specifications table
id
listing_id
swimming_pool
water_well
I need to select the specifications (checkboxes) on the same form with which I add a listing. I have created all the forms, views, models, controllers but I think I got some logic wrong.
Listing.php model
protected $table = 'listings';
public function contact()
{
return $this->BelongsTo('contacts');
}
public function specifications()
{
return $this->BelongsTo('listings_specifications');
}
Specification.php model
protected $table = 'listings_specifications';
public function listings()
{
return $this->BelongsTo('listings');
}
ListingsController.php (where the data gets saved in the database)
$listing = new Listing;
$contact = new Contact;
$listing->status = Input::get('status');
$listing->listingfor = Input::get('listingfor');
$listing->propertystatus = Input::get('propertystatus');
$listing->propertytype = Input::get('propertytype');
$listing->userid = Auth::user()->id;
$listing->location = Input::get('location');
$listing->contact_id = $contact_id;
$listing->save();
$specifications = Specification::find($id);
if( $listings->save() ) {
$specifications = new Specification;
$specifications->listing_id = $id;
$specifications->swimming_pool = Input::get('swimming_pool');
$specifications->water_front = Input::get('water_front');
$specifications->save();
}
I'm getting this error: Undefined variable: id
Where did I go wrong?
Thank you
It looks like you have some logic errors.
First of all, you are never setting $id anywhere, but that's okay because you really don't need it.
Remove the $specifications = Specification::find($id); line because that's not doing anything.
Then change your last section to something like this...
if( $listings->save() ) {
$specifications = new Specification;
$specifications->swimming_pool = Input::get('swimming_pool');
$specifications->water_front = Input::get('water_front');
$listing->specifications()->save($specifications);
}
$listing->specifications()->save($specifications); will automatically save the new specification with the correct listing_id for you.
Modify your Listing model's specifications relationship to...
public function specifications()
{
return $this->hasMany('Specification');
}
I'm assuming here one listing can have many specifications. If not, you can easily just change that to a hasOne.
You use $id in the line $specifications = Specification::find($id); but you don't define it before.

Categories