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.
Related
i have a problem that when i get data from other api and want if same title wont save to api. Each time getting data from the api is 20 and want to save it to the database without duplicate. Please help me. Thank you very much!!!
public function getTitle($title){
$title = $this->posts->where('title', $title)->get();
return $title;
}
public function getApi(Request $request){
$url = "https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=87384f1c2fe94e11a76b2f6ff11b337f";
$data = Http::get($url);
$item = json_decode($data->body());
$i = collect($item->articles);
$limit = $i->take(20); // take limited 5 items
$decode = json_decode($limit);
foreach($decode as $post){
$ite = (array)$post;
$hi = $this->getTitle($ite['title']);
dd($ite['title'], $hi);
if($ite['title']==$hi){
dd('not save');
}
else{
dd('save');
}
//dd($hi, $ite['title']);
// create post
$dataPost = [
'title'=>$ite['title'],
'description'=>$ite['description'],
'content'=>$ite['content'],
'topic_id'=>'1',
'post_type'=>$request->type,
'user_id'=>'1',
'enable'=>'1',
'feature_image_path'=>$ite['urlToImage']
];
//dd($dataPost);
//$this->posts->create($dataPost);
}
return redirect()->route('posts.index');
}
You can use first or create for saving data in database if title name is new. using firstOrNew you dont have to use any other conditions
for example:-
$this->posts->firstOrCreate(
['title' => $ite['title']],
['description'=>$ite['description'],
'content'=>$ite['content'],
'topic_id'=>'1',
'post_type'=>$request->type,
'user_id'=>'1',
'enable'=>'1',
'feature_image_path'=>$ite['urlToImage']]);
firstOrNew:-
It tries to find a model matching the attributes you pass in the first parameter. If a model is not found, it automatically creates and saves a new Model after applying any attributes passed in the second parameter
From docs
If any records exist that match your query's constraints, you may use
the exists and doesntExist methods
if($this->posts->where('title', $title)->doesntExist())
{
// save
} else {
// not save
}
I have Order model, and I want to change "status" in one of orders. I execute such a code:
$order = new Order();
$new = $order->find()->where(['status' => 'new'])->orderBy(['id' => SORT_ASC])->one();
if($new){
$new->status = "queued";
$ok = $new->save();
return true;
}
And, $new is the record that I want, so that's ok. So, when I try to save changes, it doen't do it, and $ok gives me "false". I have no idea why, I have used save() before and never have problems with it.
Update:
Found mistake, it was not connected to save() function.
Your value is not saving because of model validation, You can skip model validation by putting false.
$order = new Order();
$new = $order->find()->where(['status' => 'new'])->orderBy(['id' => SORT_ASC])->one();
if($new){
$new->status = "queued";
$ok = $new->save(false); // skip model validation
return true;
}
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.
I'm working on a php project but I have a problem with the database , I use this code to get data from the database :
public function getSeenAction(Request $request , $notificationId)
{
$sessionId = $request->headers->get('SessionID');
if( $sessionId == null )
{
//return new Response("Unauthorized",401);
}
$notificationRepo = $this->getDoctrine()->getRepository('MegasoftEntangleBundle:Notification');
$notification = $notificationRepo->findOneById($notificationId);
if($notification == null)
{
return new Response("Notification not found" ,404);
}
$seen = $notification->getSeen();
$response = new JsonResponse();
$response->setdata(array('seen'=>$seen));
$response->setStatusCode(200);
return $response;
}
I tried the same code with other tables and it worked , but whenever I retrive data from the Notification table it always give null , although the table contains the data.
$notificationRepo = $this->getDoctrine()->getRepository('MegasoftEntangleBundle:Notification');
$notification = $notificationRepo->findAll();
var_dump(notification);
Is this code returns you something ? Probably the code of your NotificationRepository.php is not good, can you put it on ?
Try using find instead of findOneById if you just want to find record by Id.
On the other hand if you want to use findOneBy the passed argument for criteria should be an array.
$result = $notificationRepo->find($notificationId);
Or
$result = $notificationRepo->findOneBy(array('id' => $notificationId));
Or
make sure you have a proper code for findOneById in your NotificationRepository.php file
Then you can check
if (!empty($result)) { ... }
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);