You need to sign in to do that
Don't have an account?
chandrashekar Jangiti
Hi friends..how we can write junction object record creation and deletion via apex code
Hi friends..
how we can write junction object record creation and deletion via apex code
how we can write junction object record creation and deletion via apex code
If any of the master records (parent) is deleted, the junction objec is automatically deleted.
create would be the same, just ve sure that you put Ids for both parent, else, junction object would have no sense.
for delete, you can simply use database.delete(<idOfTgeRecord>)
You can query the junction object with the id of one of the two objects between which the junction object is created. The junction object must have a lookup on both of the objects.
Take the example below. I have a junction object between pricebook and products named PricebookEntry. I have the Id of the product and I want to find the junction object record so I'll simply query it with the help of product Id.
Like this:
I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.
Thanks and Regards,
Deepali Kulshrestha
www.kdeepali.com
-> Every junction object is created between two sObjects or two Custom Objects.
-> Junction objects are used to create many to many relationships between objects
-> Junction Object contains ids of both objects that it is created for.
Let's take an example, In salesforce there are two sObjects (Pricebook and Product) and they contain a junction object named as PricebookEntry
you can also see the relationship between objects using the below link:
https://salesforce.stackexchange.com/questions/215991/salesforce-data-design-tool
* First we need to make a Product because its ID id required in the creation of PricebookEntry
Product2 p = New Product2();
p.Name = 'hello';
p.IsActive = True;
insert p;
* Now we need to create Pricebook because its ID id required in the creation of PricebookEntry
PriceBook2 pb = new PriceBook2();
pb.Name = 'Algo12';
pb.IsActive = true;
insert pb;
* Now its time to create PriceBookEntry
PriceBookEntry pbe = New PriceBookEntry();
pbe.Product2Id = p.Id; //parentID
pbe.Pricebook2Id = pb.id; //ParentID
pbe.IsActive = True;
pbe.UnitPrice = 100;
insert pbe;
-> If you want to delete any ParentID then your junction object is also going to delete since the child record (PriceBookEntry) does not have any parent.
-> And if you delete any juction object record then both its parent isn't going to delete.
-> For deleting a record you just need to get that record from database by querying it in apex code and simply write:
delete pbe; // for above example
I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.
Thanks and Regards,
Ajay Dubedi
www.ajaydubedi.com