I create a Employee object where I want to show Lookup Relationship field for Lead. Employee records are coping from Lead. so how to do ?
Actully I wrote in class,
emp.Source_Lead__c = lead.id; // emp is Employee object & lead is Lead object.
but it shows me Name, CompanyName in lookup so it wont access.
like :
Source Lead : eabc exyz, ecompany
Help me....
If you're talking about new employee / edit employee form - yes, you pass an Id. You're doing it right. The tricky part is that you can't immediately use "dots" to show fields from Lead.
After establishing the link and saving you will have to query for lead fields. Something like this (your question isn't too clear, I don't know if this is on one page or 2).
Employee__c emp = new Employee__c();
// ... fill fields as needed
emp.Source_Lead__c = lead.Id;
insert emp;
// And later you can query
emp = [SELECT Id, Name, Source_Lead__c, Source_Lead__r.Name, Source_Lead__r.Custom_Field__c
FROM Employee__c WHERE Id = :emp.Id];
System.debug(emp.Lead_Source__r.Name); // now it will work
Related
In Salesforce I would like to retrieve AccountIds where its related Contact FirstName must have values in list of String. List of string is {'Test','User'}. I would need to find all Accounts where Contact first Name has both Test and User as related Contacts,
I am trying as below but the below query will show accounts where even 1 value matches as Contact First Name.
List<String> names = new List<String>{'Test','User'}; List<Account> accountList = [ Select Id from Account Where Id IN (Select AccountId FROM Contacts where FirstName LIKE :names)];
Please help
SELECT Id, Name
FROM Account
WHERE Id IN (SELECT AccountId FROM Contact WHERE LastName = 'Test')
AND Id IN (SELECT AccountId FROM Contact WHERE LastName = 'User')
But it'll work only 2 times, you can't write 3rd "IN" like that (see here).
If you need a more generic solution that can take lists of any size you'd have to run "my" queries in loop, 2 names at a time, save results to some Set<Id> or Map, play with functions like myset.retainAll(idsFromCurrentLoopQuery)... Of course query in a loop is bit evil too.
I would like to keep an updated copy of some salesforce data in a database.
e.g. a table with all contacts
However, it is impractical to truncate the table and to query all data again on a frequent basis.
Is there some way to only query changed contacts since the last sync?
e.g. I would run an hourly job that gets all contacts that changed within the last hour.
In addition, how could I deal with deleted contacts. I assume that if there is a way to get changed ones this might not include deletions.
To query all contacts modified since a particular date/time:
Datetime OneHourAgo = System.now().addHours(-1);
List<Contact> AllContactsModfiedSinceDateTimeX = [SELECT Id FROM Contact WHERE SystemModStamp >= : OneHourAgo];
Same query but including all deleted contacts:
Datetime OneHourAgo = System.now().addHours(-1);
List<Contact> AllDeletedContactsModfiedSinceDateTimeX = [SELECT Id FROM Contact WHERE SystemModStamp >= : OneHourAgo AND isDeleted = TRUE ALL ROWS]; //"ALL ROWS" must be included when using isDeleted = TRUE
we have a problem to query our database in a meant-to-be fashion:
Tables:
employees <1-n> employee_card_validity <n-1> card <1-n> stamptimes
id id id id
employee_id no card_id
card_id timestamp
valid_from
valid_to
Employee is mapped onto Card via the EmployeeCardValidity Pivot which has additional attributes.
We reuse cards which means that a card has multiple entries in the pivot table. Which card is right is determined by valid_from/valid_to. These attributes are constrained not to overlap. Like that there's always a unique relationship from employee to stamptimes where an Employee can have multiple cards and a card can belong to multiple Employees over time.
Where we fail is to define a custom relationship from Employee to Stamptimes which regards which Stamptimes belong to an Employee. That means when I fetch a Stamptime its timestamp is distinctly assigned to a Card because it's inside its valid_from and valid_to.
But I cannot define an appropriate relation that gives me all Stamptimes for a given Employee. The only thing I have so far is to define a static field in Employee and use that to limit the relationship to only fetch Stamptimes of the given time.
public static $date = '';
public function cardsX() {
return $this->belongsToMany('App\Models\Tempos\Card', 'employee_card_validity',
'employee_id', 'card_id')
->wherePivot('valid_from', '>', self::$date);
}
Then I would say in the Controller:
\App\Models\Tempos\Employee::$date = '2020-01-20 00:00:00';
$ags = DepartmentGroup::with(['departments.employees.cardsX.stamptimes'])
But I cannot do that dynamically depending on the actual query result as you could with sql:
SELECT ecv.card_id, employee_id, valid_from, valid_to, s.timestamp
FROM staff.employee_card_validity ecv
join staff.stamptimes s on s.card_id = ecv.card_id
and s.stamptimes between valid_from and coalesce(valid_to , 'infinity'::timestamp)
where employee_id = ?
So my question is: is that database desing unusual or is an ORM mapper just not capable of describing such relationships. Do I have to fall back to QueryBuilder/SQL in such cases?
Do you suit your database model towards ORM or the other way?
You can try:
DB::query()->selectRaw('*')->from('employee_card_validity')
->join('stamptimes', function($join) {
return $join->on('employee_card_validity.card_id', '=', 'stamptimes.card_id')
->whereRaw('stamptimes.timestamp between employee_card_validity.valid_from and employee_card_validity.valid_to');
})->where('employee_id', ?)->get();
If your Laravel is x > 5.5, you can initiate Model extends the Pivot class I believe, so:
EmployeeCardValidity::join('stamptimes', function($join) {
return $join->on('employee_card_validity.card_id', '=', 'stamptimes.card_id')
->whereRaw('stamptimes.timestamp between employee_card_validity.valid_from and employee_card_validity.valid_to');
})->where('employee_id', ?)->get();
But code above is only translating your sql query, I believe I can write better if I know exactly your use cases.
If i need to creat an Order , I need to first creat an Account and then assign the AccountId to the Order, like the following
Account a = new Account();
a.Name = 'Test';
insert a;
Order order = new Order(
AccountId = a.Id,
Status='Draft',
EffectiveDate = Date.today());
insert order;
Is there a way I can simply create an Order and the dependent objects will be created or is there a way to get what Sobject field the AccountId of the order is related to ?
There is no way for Salesforce to automatically create the dependent sObjects, they will have to be inserted.
Regarding your second question (retrieving the type of sObject from the field name) you can check out this question on Salesforce StackExchange. Below is that code being ran for the AccountId field on the Order object:
Relatively new to JPA, so I have one kind of architectural question.
Let's say I have tables EMPLOYEE and DEPARTMENT with many to one relationship (i.e. many employees work for one department):
EMPLOYEE
EMPLOYEE_ID
EMPLOYEE_NAME
DEPARTMENT_ID
DEPARTMENT
DEPARTMENT_ID
DEPARTMENT_NAME
So I can define proper entities for Employee and Department, there's no problem. However, in one view I would like to display list of departments with number of employees working for that department, something like this:
SELECT D.DEPARTMENT_NAME,
(SELECT COUNT(*) FROM EMPLOYEE E WHERE E.DEPARTMENT_ID = D.DEPARTMENT_ID) NUMBER_OF_EMPLOYEES
FROM DEPARTMENT D
I'm just not sure what is the right strategy to accomplish this using JPA...
I don't want to always fetch number of employees for Department entity, as there is only one view when it is needed.
It looks like Hibernate's #Formula would be one possible approach, but afaik it does not conform with JPA standard.
You can create any object in your QL using the "new" syntax - your class just needs a constructor that takes the values returned by your query.
For example, with a class like DepartmentEmployeeCount, with a constructor:
public DepartmentEmployeeCount(String departmentName, Integer employeeCount)
you could use QL something like:
SELECT NEW DepartmentEmployeeCount(D.DEPARTMENT_NAME, count(E.id)) from Department D left join D.employees E GROUP BY D.DEPARTMENT_NAME
Or if you were just selecting the count(*) you could simply cast the query result to a Number.
Alternatively, to do the same without the DepartmentEmployeeCount class, you could leave out the NEW, so:
SELECT D.DEPARTMENT_NAME, count(E.id)
This would return a List<Object[]> where each list item was an array of 2 elements, departmentName and count.
To answer your later question in the comments, to populate all fields of a Department plus a transient employeeCount field, one suggestion would be to do 2 queries. This would still be more efficient than your original query (a subselect for each employee count).
So one query to read the departments
SELECT D from Department D
giving you a List<Department>
Then a 2nd query returning a temporary array:
SELECT D.DEPARTMENT_ID, count(E.id) from Department D left join D.employees E GROUP BY D.DEPARTMENT_ID
giving you a List<Object[]> with DEPARTMENT_ID and count in it.
Then you use the 2nd list to update the transient count property on your first list.
(You could try selecting into a Map to make this lookup easier, but I think that's a Hibernate feature).
Option 1: I suggested this since you didn't like the constructor route MattR was suggesting. You mentioned the word "view" several times, and I know you were talking about the view to the user, but why not setup a view in your database that includes the computed columns and then create a read-only entity that maps to the computed columns?
Option 2: In response to your comment about not wanting to create a view. You could create a container object that holds the entity and the calculated column, then much like MattR suggests, you use a new in your select. Something like:
public class DepartmentInfo {
private Department department;
// this might have to be long or something
// just see what construct JPA tries to call
private int employeeCount;
public DepartmentInfo( Department d, int count ) {
department = d;
employeeCount = count;
}
// getters and setters here
}
Then your select becomes
SELECT new my.package.DepartmentInfo( D,
(SELECT COUNT(*) FROM EMPLOYEE E WHERE E.DEPARTMENT_ID = D.DEPARTMENT_ID))
FROM DEPARTMENT D
With that you can use the DepartmentInfo to get the properties you are interested in.
You could create a member in your entity as an additional column, and then reference it with an alias in your query. The column name in the #Column annotation must match the alias.
Say, for your original query, you can add a countEmployees member as following. Also add insertable=false and updatable=false so the entity manager wont try to include it in insert or update statements:
public class Department {
#Column(name="DEPARTMENT_ID")
Long departmentId;
#Column(name="DEPARTMENT_NAME")
String departmentName;
#Column(name="countEmployees", insertable=false, updatable=false)
Long countEmployees;
//accessors omitted
}
And your query:
SELECT D.DEPARTMENT_NAME,
(SELECT COUNT(*) FROM EMPLOYEE E WHERE E.DEPARTMENT_ID = D.DEPARTMENT_ID) AS countEmployees
FROM DEPARTMENT D
This also applies when working with Spring Data Jpa Repositories.