Display Books with Their Authors
Follow Along with Trail Together
Want to follow along with an expert as you work through this step? Take a look at this video, part of the Trail Together series.
(This clip starts at the 6:52 minute mark, in case you want to rewind and watch the beginning of the step again.)
Introduction
In this step you will continue to build Books4Everyone’s perfect home page. They love that you can display book titles on the home page, and it gave them ideas about other information they want to display. Their developer gave you a few new ideas for what they would like to see on the home page.
Understand How Relationships Work in Salesforce
In SOQL we use relationship queries to get the same data you would get from a join in SQL. We can do this only if the two objects we’re querying are related. Thankfully, the Books4Everyone package already built out all the relationships we need.
We’re going to write a few of these relationship queries in order to build up to the ultimate request from Books4Everyone. To test each query, we’ll have to update our Apex class and Lightning component.
Write a Right Outer Join
- Open the Developer Console and open the Books4EveryoneHomeController Apex class.
- Add the following block of code after the first method.
@AuraEnabled public static List<Book__c> getBooksAndAuthor() { return; //Your Query here! }
Here's the first query Books4Everyone suggested.SELECT a.Name, b.Name, b.Description FROM Author a RIGHT JOIN Book b ON (b.Author=a.Name)
In SOQL we write it like this.SELECT Name, Description__c, Author__r.Name FROM Book__c
- Add the new SOQL query to your method. It should now look like this.
@AuraEnabled public static List<Book__c> getBooksAndAuthor() { return [SELECT Name, Description__c, Author__r.Name FROM Book__c]; }
Now let’s update our home page Lightning component. - In the Developer Console, open the Books4EveryoneHome Lightning component.
- Update the table to look like this.
<table class="slds-table slds-table_bordered slds-table_cell-buffer"> <thead> <tr class="slds-text-title_caps"> <th scope="col">Book Titles</th> <th scope="col">Book Descriptions</th> <th scope="col">Author</th> </tr> </thead> <tbody> <aura:iteration items="{!v.Books}" var="books"> <tr scope="row"> <td> {!books.Name}</td> <td> {!books.Description__c}</td> <td> {!books.Author__r.Name}</td> </tr> </aura:iteration> </tbody> </table>
- Open the Books4EveryoneHomeControllerJavaScript file and update the action to call our new function.
var action = component.get("c.getBooksAndAuthor");
The controller code should now look like this.({ doInit: function(component, event, helper) { var action = component.get("c.getBooksAndAuthor"); action.setCallback(this, function(data) { component.set("v.Books", data.getReturnValue()); console.log(data.getReturnValue()); }); $A.enqueueAction(action); } })
- Save all files and refresh your page!