How do I delete only the selected data? - spring-boot

When I select a user and an item that a user is using and press the button, I want only that item to disappear. However, the code I created now removes all items the User has.
When adding selected data, I inserted and saved using .add and .save. But I don't know how to delete and save it.
-- spring boot (controller)
#PutMapping(value = {"/users/{id}", "/profileModi/{id}", "/users/productSetting/{id}"})
public ResponseEntity<User> updateUser(#PathVariable("id") long id, #RequestBody User user) {
Optional<User> userData = userRepository.findById(id);
if (userData.isPresent()) {
User _user = userData.get();
_user.setProductInfo(user.getProductInfo());
_user.setRoles(user.getRoles());
_user.setUsername(user.getUsername());
_user.setEmail(user.getEmail());
_user.setPassword(user.getPassword());
_user.setDelYn(user.isDelYn());
return new ResponseEntity<>(userRepository.save(_user), HttpStatus.OK);
} else {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
-- vue.js
<b-button variant="danger" class="btn btn-fw"
#click="updateProductUser()"
>
cancle
</b-button>
--vue.js (script)
updateProductUser() {
var data = {
id:this.currentUser.id,
email:this.currentUser.email,
delYn:this.currentUser.delYn,
password:this.currentUser.password,
username:this.currentUser.username,
roles:this.currentUser.roles
};
ProductSettingUserDataService.update(this.currentUser.id, data)
.then(response => {
this.currentUser = response.data;
console.log(this.currentUser);
})
.catch(e => {
console.log(e);
});
},
Originally, there was a productInfo table in the User table, and I used a simple method of deleting data by not writing this table. But now I only want to delete one of the data of the productInfo I have selected.
Can you tell which code should be inserted in the controller to be deleted and saved?
I also tried with #DeleteMapping. But it failed...
Relationship table between user and product
As you can see in the picture, User and productInfo have a 1:n relationship. For example, I want to delete only product_id = 12 out of 3 products with user_id = 1.
++ users Table
users
++ productInfo Table
productInfo
The productInfo table exists in the users table.
++ console window
console

Your controller is replacing all the data from the user and your vue.jsscript is not sending product data:
// Data sent by the front
var data = {
id:this.currentUser.id,
email:this.currentUser.email,
delYn:this.currentUser.delYn,
password:this.currentUser.password,
username:this.currentUser.username,
roles:this.currentUser.roles
};
// Controller PUT
User _user = userData.get();
// The front is not sending any productInfo
_user.setProductInfo(user.getProductInfo());
_user.setRoles(user.getRoles());
_user.setUsername(user.getUsername());
_user.setEmail(user.getEmail());
_user.setPassword(user.getPassword());
_user.setDelYn(user.isDelYn());
return new ResponseEntity<>(userRepository.save(_user), HttpStatus.OK);
Since you are not sending product info, the previous product info is deleted. Your front need to send the product info data that you want to preserve.

let me see user table's data. i guess that your userInfo and your productInfo share one table; If you have a productinfo table, you shoud transfer a productId from vue page instead of userId

Related

INSERT into the table and return id of the record Supabase JS

Based on the docs, inserting a new record
const { error } = await supabase
.from('countries')
.insert({ name: 'Denmark' })
returns
{
"status": 201,
"statusText": "Created"
}
For columns that are Is Identity, it automatically assigns a sequential unique number to the column.
How to get the ID of the newly inserted record on Supabase with JavaScript client?
You can add .select() after your insert statement in order to get the newly inserted record.
const { data, error } = await supabase
.from('countries')
.insert({ name: 'Denmark' })
.select()
You will see the inserted record inside data variable. Note that retrieving the inserted record requires you to have not only insert permission, but select permission on RLS policies.
On a side note, you can click on the buttons on the right of the docs to view different use cases. You can see this example on Create a record and return it example.

Laravel 4 get the id of created field

I am developing a booking form that has data that will fill two tables, users and booking table. In the controller I am getting the input fields and inserting the user fields first, then I do the insert for the booking but I need the id of the user I've just inserted, I have tried many methods without success, this is what I have done in my controller:
$User = new User;
User::create(array(
'lastname'=>Input::get('lastname'),
'name'=>Input::get('name'),
'address'=>Input::get('address'),
'cell_phone'=>Input::get('cell_phone'),
'email'=>Input::get('email')
));
// I try to get the inserted user id here
$userInserted=$User->id;
// And here I insert the booking with the user_id
$Booking = new Booking;
Booking::create(array(
'apartment_id'=>Input::get('apartment_id'),
'user_id'=>$userInserted,
'date_ini'=>Input::get('date_from'),
'date_fin'=>Input::get('date_to'),
'stay_cost'=>Input::get('stay_cost'),
'stay_days'=>Input::get('stay_days')
));
The problem is I am not getting the user Id. Any idea way?
thanks in advance
You are assignin it wrong.
$newUser = User::create(...);
$insertedUserId = $newUser->id;
Your $User = new User; makes no sense, because it just initializes emty User Object, but User::create sends query to DB to store data and returns inserted Object.

Set passed value in my ActionResult

I have two independent classes that model my tables. First when a new user is created, the user does not have a record in the certificate tables. So in the view for the certificates I have added a button to add certificates details for this new user.
This is my code for the user view: I omitted the paging/search and filter code to make it simple
public ActionResult Index()
var recipients = from s in db.User
select s;
return View(recipients.ToList());
This is the details view showing related data:
public ViewResult Details(int id)
{
var certificateDetails = db.Certificate.Where(p => p.ID == id);
return View(certificateDetails);
}
Adding a new user means also adding a new certificates details. I want when a user clicks details for the a particular user if those details aint around to be redirected to a create certificate view with both User.ID and CertificateID set. In fact CertificateID is AI but ID from User is foreign key.
I would have used Fluent API but am not good with it either so have to handle this seemingly small challenge in code.
If I understand your question correctly, you want it so that when you view Details(), if the certificate details don't exist, then redirect to a page to create them?
Just check whether or not the entity exists. If it doesn't, return a RedirectToAction() and pass whatever data you need in the route data collection.
public ViewResult Details(int id)
{
var certificateDetails = db.Certificate.FirstOrDefault(p => p.ID == id);
if (certificateDetails == null)
return RedirectToAction("Create", "Certificate", new { userId = id });
return View(certificateDetails);
}
You'll also need to create a Certificate controller with a Create() action.

how to create a document in a mongodb collection and update another collection in the same time

here is my problem
i have three schema
var UserSchema = new Schema({
username:String,
email:String,
hashed_password:String,
salt:String,
shop_id:{type:Schema.Types.ObjectId,ref:'Shop'},
})
var ShopSchema = new Schema({
owner_id:{type:Schema.Types.ObjectId,ref:'User'},
owner_real_id:String,
owner_real_name:String,
owner_real_location:String,
shop_name:String,
sell_product_ids:[Schema.Types.ObjectId],
})
var ProductSchema = new Schema({
})
it is necessary to sign up the userschema to use the app, but unnecessary to sign up the shopschema unless the user want to sell some stuff. however when the user do sign up the shopschema i need to update the userschema with the shop's _id,
so here is what i did
create the document in shop collection
find the shops _id
update the user collection
as u can see i query the datebase three times,so i was wondering if this can be done in one query in order to save time like
Shop.create(regist_data,function(){
//update the user collection here
})
Just in case u wondering why i need this, its becase i use 'passport' to log user in, and i want to acess the ProductShcema by shop's _id in the req.user, otherwise every time i want to acess the ProductShcema i nend to find the shop's _id and then get the product that belong to the shop's _id.
any way if u have better solution,please let me know.thanx!!!
sorry i think i should've read the mongoose doc more carefully
here is what i figure out
Shop.create(regist_data,function(err,shop){
console.log('shop = '+shop);
User.findByIdAndUpdate(req.user.id,{ $set: { shop_id: shop._id }},{new:true},function(err,data){
if(err){
console.log(err)
}
console.log('new user = '+data);
})
})
it create the shop document and update the users collection , it works for me.

Displaying records from database which are equal to logged on user

I have created an MVC3 application which needs to show user specific data. The problem I am having is trying to display records which are equal to #user.Identity.Name.
The following Linq to SQL has been used to try to accomplish this:
public ActionResult Index()
{
using (var db = new mydatEntities())
{
var details = from t in db.testadtas
where t.UserID == Viewbag.UsersRecord
select t;
return View();
}
}
(Update)
New to c# and Linq and finding it hard to write a query which will only display the logged on users records.
I have used the code below
MembershipUser currentUser = Membership.GetUser (User.Identity.Name, true /* userIsOnline */);
Viewbag.UsersRecord = currentUser.ProviderUserKey;
I have then input the Viewbag.UserRecord into a textbox which updates a database field with the UserID in a table I have created.
I now want to write a linq query to say if UserID = Viewbag.UserRecord then show record with the UserID only
Is this a correct method to use for showing logged on user records?
or is there any other way which I can implement this in MVC3?
Just use HttpContext.User.Identity.Name

Resources