Simple question. What does this code do?
public function claim(Request $request){
$comment = Comment::where('key',$request->key)->where('is_deleted','No')->first();
if(!empty($comment)){
return 1;
}else{
return 0;
}
}
I've tried changing what keys it's trying to match, but then it breaks.
EDIT:
Based on the answers I've got so far, it sounds like its checking for comments who's key matches the requested one. When I change the code to this, the form stops responding:
public function claim(Request $request){
$user = User::where('key',$request->key)->where('is_deleted','No')->first();
if(!empty($user)){
return 1;
}else{
return 0;
}
}
EDIT 2:
I have a table called Posts and a table called Users. Each entry on the Post table has a unique ID, a Title, and a Key (B_Key). That Key matches only 1 entry in the Users table. Each User has 3 keys (A_Key, B_Key, C_Key).
I'm trying to make my form ask for A_Key, then check if the User with that A_Key also has the B_Key that was used to publish this specific post. I tried writing a SQL query but have failed. Here is is:
$post = "SELECT posts.id, users.A_Key FROM posts INNER JOIN posts ON posts.id=users.A_Key WHERE posts.is_deleted = No";
if(!empty($post)){
return 1;
}
else{
return 0;
}
}
If there is any comment which is related with key and if didn't has then result will return 1 (true) else 0 (false)
Related
I tried to accomplish a multiple where clause but failed. I want to check if the current Date of the user is equal to created_at and the second clause would be if the user has an entry by user id. I am working on a fitness app where the User can track the km he has run. And rather to create in a database table new entries just add them to the existing entries.
My Question is focused on the problem with the if clause because the variable $hasUserEntries is not equal to null but there is no entry in the database table. It is empty.
I tried instead of using get() I used first(). But the problem is that I wasn't able to use Carbon::today() or it was maybe that I use 3 values in the where clause which I need because I can't get the created_at date only the Date YYYY-MM-DD. At the first() Statement I used a hardcoded DateTime to check with created_at and it worked. But I think I must not explain why hardcode is not optimal.
I searched on Stackoverflow and find that most answers were about using get(). It is fine but why does my else get triggered because from my point of view the database is empty(Null) so the if($hasUserEntries==null)should be triggered.
public function add_km_to_progressbar(Request $request, TrackKM $trackKM)
{
$track_dailies = new TrackDaily();
$track_dailies->user_id = \Auth::user()->id;
$amount_runned_km = $request->input('amount_runned_km');
$amount_runned_km = (int)$amount_runned_km;
$track_dailies->amount = (int)$amount_runned_km;
$track_dailies->type = 1;
$check_requirements = [
'user_id'=>\Auth::user()->id,
'created_at'=>'Carbon::today()'
];
$hasUserEntries = DB::table('track_dailies')
->where('user_id','=',\Auth::user())
->where('created_at','>=',Carbon::today())
->get();
if ($hasUserEntries == null) {
return dd('does not work');
} else {
return dd('does work');
}
}
Expected Result should be the triggering of the if statement because if the database table is empty, the user id does not exist or the date of created_at is not the same as the current date then should be triggered if($hasUserEntries==null). I want to create there a new row if this condition == null in the database.
Actual Result if($hasUserEntries==null) is true even though that the database table is empty. I think that the method get() has values saved that are not related to the database.
I hope that you can help me out.
i think what you should have done is checking to see if the record exist in the database before proceeding...
$checkifuserExist= DB::table('track_dailies')->where('user_id','=',\Auth::user())->where('created_at','>=',Carbon::today())->count();
if($checkifuserExist>0)
{
//proceed to query for fitness
}
else
{
//do something else...
}
with this, it will not throw error!
Try this if case intead:
if (is_empty($hasUserEntries))
$checkifuserExist= DB::table('track_dailies')->where('user_id','=',\Auth::user())->where('created_at','>=',Carbon::today())->count();
if($checkifuserExist>0)
{
//if user really exists
if( $hasUserEntries = DB::table('track_dailies')->where('user_id','=',\Auth::user())->where('created_at','>=',Carbon::today())->first())
{
//update the value of the amount
}
else{
//insert new record
}
}
else
{
// if the user does not exist, do something else...
}
remember theres no way the record for user_id would be null because first there has to be record inside the db
I have 2 models Tour.php
public function Itinerary()
{
return $this->hasMany('App\Itinerary', 'tour_id');
}
and
Itinerary.php
public function tour()
{
return $this->belongsTo('App\Tour', 'tour_id');
}
tours table:
id|title|content
itineraries table:
id|tour_id|day|itinerary
I have used vue js to create or add and remove input field for day and plan dynamically. And used the following code in tour.store method to insert into itineraries table:
$count = count($request->input('day'));
$temp_day = $request->input('day');
$temp_itinerary = $request->input('itinerary');
for($i = 0; $i < $count; ++$i)
{
$itinerary = new Itinerary;
$itinerary->tour_id = $tour->id;
$itinerary->plan = $temp_itinerary[$i];
$itinerary->day = $temp_day[$i];
$itinerary->save();
}
And was successful in inserting the records.And applied same code in tour.store method. Instead of updating the rows, it inserted new rows to the table. What would be the best solution for this ?
For updation try this code
$itinerary = Itinerary::find($tour_id);
$itinerary->plan = $temp_itinerary[$i];
$itinerary->day = $temp_day[$i];
$itinerary->save();
The way you are using is to insert/create new records. To update you can use.
Itinerary::find($tour_id)->update(
['column_name'=> value]
);
Where find method takes a primary key of the table.
This will update your existing record. You can update as many columns as you want just pass in array update takes. You can also use save method as mentioned in other answer.
Check Laravel Update Eloquent
EDIT
$iterneary = Itenerary::where('tour_id', $tour_id)->first();
Now you can update this iterneary object to whatever you want.
this is how i did it. First saved all the tours in $tours[] array.
foreach($tours as $tour) {
$itinerary->tour()->updateOrCreate(['id'=> $tour['id']],$tour);
}
updateOrCreate because you may need to add new tours while updating. I know this doesnt answer your issue exactly but this could atleast give you an idea.
I want to delete all record according to id and then insert record in same table,I tried many ways but can't find solution please help me.
Basically as per the document id i want to delete all document but it is not working.
Here is my controller code:
foreach ($receievers as $user) {
$this->shareRepo->deleteSharedDoc($resourceId);
$this->shareRepo->saveshareSharedDoc($resourceId, $user->id,$this->getCurrentUser());
}
The repository code:
function saveSharedDoc($resourceId, $sharedWith, $resourceOwnerId){
$shareDocs = new ShareDocs;
$shareDocs->resource_id = $resourceId;
$shareDocs->shared_with = $sharedWith;
$shareDocs->user_id = $resourceOwnerId;
$shareDocs->shared_on = $this->getCurrentDateTime();
$shareDocs->token = str_random(20);
$shareDocs->save();
return $shareDocs->token;
}
function deleteSharedDoc($resourceId){
$network = ShareDocs::where('resource_id','=',$resourceId);
$result=$network->delete();
return $result;
}
Please help me out
It's seems you're doing it correctly. But there are two things that you have to change.
You are calling to saveshareSharedDoc method within foreach loop to save data. but actual method name on your repo is saveSharedDoc. (there two "share" words on loop)
you can return deleted rows directly return ShareDocs::where('resource_id', $resourceId)->delete();
I have a mysql table with composite keys ( user_id , category_id );
I am trying to update the last access for these records as following
$userCategory = new UserCategory;
$userCategory->user_id = 1;
$userCategory->category_id = 15;
echo $userCategory->isNewRecord; //always true
$userCategory->last_access = Now();
$userCategory->save();
The {$userCategory->isNewRecord} and when I try to save() the MySQL generates a duplicate error for the composite Primary keys.
I also added this to UserCategory model but didn't help
public function primaryKey() {
return array('user_id', 'category_id');
}
****Update:
Sorry for the confusion. My question is how to achieve the same result as "ON DUPLICATE KEY UPDATE" in the Yii framework. In other words, how to do the insert or update in one SQL query. if you look at the source code for save()
public function save($runValidation=true,$attributes=null)
{
if(!$runValidation || $this->validate($attributes))
//checking if new record
return $this->getIsNewRecord() ? $this->insert($attributes) : $this->update($attributes);**
else
return false;
}
Actually, the problem is that if isNewRecord is always true, it means that Yii is going to use an INSERT statement instead of an UPDATE statement when saving the model to the database.. that is why you always get the duplicate pk error, even if it's composite.
Here is the official documentation about IsNewRecord . So, the problem is that you're using
$userCategory = new UserCategory; //Always a new record, tries to INSERT
So to resolve this you have to find the record and evaluate if it is found before saving it, instead. Documentation can also be read Here about the find() family of methods and their return value, the return values of the find() methods vary slightly on their nature:
find..() returns the record found or NULL if no record is found.
findAll..() returns an array containing all the records found or an empty array if no records are found.
You can use this return value to differentiate wether a primary key exists or not:
$userCategory = UserCategory::model()->findByAttributes(array('user_id '=>1,'category_id '=>15));
// if user does not exist, you need to create it
if ($userCategory == NULL) {
$userCategory = new UserCategory;
$userCategory->user_id = 1;
$userCategory->category_id = 15;
}
echo $userCategory->isNewRecord; //you will see the difference if it does exist or not exist
$userCategory->last_access = Now();
$userCategory->save();
This will ensure that the framework uses the INSERT or UPDATE statement correctly, avoiding the duplicate PK error you're getting.
Edit: Enhanced the example code to properly populate the record when it's new.
In your model, add the following method:
/**
* Uses the primary keys set on a new record to either create or update
* a record with those keys to have the last_access value set to the same value
* as the current unsaved model.
*
* Returns the model with the updated last_access. Success can be checked by
* examining the isNewRecord property.
*
* IMPORTANT: This method does not modify the existing model.
**/
public function updateRecord(){
$model = self::model()->findByPk(array('user_id'=>$this->user_id,'category_id'=>$this->category_id));
//model is new, so create a copy with the keys set
if(null === $model){
//we don't use clone $this as it can leave off behaviors and events
$model = new self;
$model->user_id = $this->user_id;
$model->category_id = $this->category_id;
}
//At this point we have a model ready for saving,
//and don't care if it is new or not
$model->last_access = $this->last_access;
$model->save(false);
return $model;
}
The above is inspired by a more general method that I use a lot to do a create-or-find-if-already-exists process.
Use the following code to execute this.
$userCategory = new UserCategory;
$userCategory->user_id = 1;
$userCategory->category_id = 15;
echo $userCategory->isNewRecord; //always true
$userCategory->last_access = Now();
$userCategory = $userCategory->updateRecord();
Note that only the last line is different from your code. The fact that the instance of the model declared with new UserCategory is not altered is intended behavior.
You can then verify in your code whether or not the model saved with the following:
if(!$userCategory->isNewRecord){
echo 'save succeeded';
}
else{
echo 'save failed';
}
If you're trying to update, you should load record, instead of creating a new one.
UserCategory::model()->findByPk(array('user_id'=> 1,'category_id '=> 15));
$userCategory->last_access = Now();
$userCategory->save();
in UserCategory.php
public function isNewRecord()
{
$result = $this->findByAttributes(array('user_id'=>$this->user_id,'category_id'=>$this->category_id));
if($result === NULL)
{
return true;
}
return false;
}
then in the controller
$userCategory = new UserCategory;
$userCategory->user_id = 1;
$userCategory->category_id = 15;
echo $userCategory->isNewRecord();
----
Another option is to modify the model to change the condition on the save function then call the parent save function: (this code goes in the UserCategory model)
public function save($runValidation=true,$attributes=null) {
$exists = UserCategory::model()->findByAttributes(array('category_id'=>$this->category_id,'user_id'=>$this->user_id));
if($exists) {
$this->isNewRecord = false;
}
return parent::save($runValidation,$attributes);
}
I just did a test and it seems to work correctly. You should just be able to do this:
$userCategory = new UserCategory;
$userCategory->user_id = 1;
$userCategory->category_id = 15;
$userCategory->last_access = Now();
$userCategory->save();
Should insert or update based off of whether it finds the record, so you don't have to change any of your other code.
I would like to ask if its possible to put a Conditional for the UPDATE. First of all I have two tables.
billing_records:
brecord_id (PK)
date_billed
monthly_rent
water
electricity
total_payable
status (paid/unpaid)
payment_records
payment_id (PK)
date
type_payment (cash/cheque/on_bank)
amount_payable
change
balance
cheque_number
bank_number
brecord_id (FK)
I would like the code to go like this during insertion records on database:
IF balance==0
UPDATE status to 'paid' from billing_records TABLE
else
UPDATE total_payable(of billing_records) = balance(of payment_records)
During submit button I have two actions to make, to insert data in payment_records and UPDATE billing_records. I don't have problems inserting data in payment records, only updating the billing_records.
I'm having trouble in this line on my Controller
// 4. call model to save input to database table
$this->m_account_statement->insertPayableRecords($data);
$this->m_account_statement->changeStatusToPaid($brecord_id);
Here is my code:
Controller:
public function managePayment($brecord_id=0){
if($this->_submit_validate_payment($this->input->post('type_payment'))===FALSE){
$row = $this->m_account_statement->payableRecord($brecord_id);
$data['amountPayable'] = $row->result();
$data['brecord_id'] = $brecord_id;
return $this->load->view('admin/vrecord_payment',$data);
} else {
// 2. get the inputs
$data['payment_id'] = $this->input->post('payment_id');
$data['amount_payable'] = $this->input->post('amount_payable');
$data['amount_received'] = $this->input->post('amount_received');
$data['type_payment'] = $this->input->post('type_payment');
$data['cheque_number'] = $this->input->post('cheque_number');
$data['bank_number'] = $this->input->post('bank_number');
$data['balance'] = $this->input->post('balance');
$data['change'] = $this->input->post('change');
$data['brecord_id'] = $this->input->post('brecord_id');
$data['date'] = $this->input->post('date_transaction');
// 4. call model to save input to database table
$this->m_account_statement->insertPayableRecords($data);
$this->m_account_statement->changeStatusToPaid($brecord_id);
// 5. confirmation of registration
$this->session->set_flashdata('message',' Successfully Record Payment');
redirect('caccount_statement/displayTenants');
}
}
Model:
public function changeStatusToPaid($billing_id)
{
$this->db->query("UPDATE billing_record SET status = 'paid' WHERE brecord_id = $billing_id");
}
public function insertPayableRecords ($data){
if($this->db->insert('payment_record', $data)){
return TRUE;
}
return FALSE;
}
It is possible to put a condition you can use this flow.
if balance==0
//then fetch a record for status
//means run a query to get status
//now update
else
// select some different values for update
// now update query with fetched values
public function managePayment($brecord_id=0){
//check if id is present or not like this:
if ($brecord_id > 0) {//Update
// ... put your update code ...
} else { //Add
// ... put your add code ...
}
}