Table :
this is table name
Requirement :
Using RestAPI call populate unique cateID, categoryName , but I am getting the whole record.
Table
Table Data which I am using
Code Description :
Repository :
#Repository
public interface CategoryRepository extends JpaRepository<xCategory,Integer>
{
// #Query("SELECT DISTINCT a.catID,a.categoryName FROM ccCategory a order by categoryName asc")
#Query("SELECT DISTINCT a.catID, a.categoryName FROM xCategory a order by categoryName asc")
List<ccCategory> getCategoryName();
}
Rest Controller:
#RestController
#CrossOrigin(origins = "http://localhost:4200", maxAge = 3600)
public class HomeResource {
private final Logger log = LoggerFactory.getLogger(HomeResource.class);
#Autowired
CategoryRepository categoryRepository;
#GetMapping("/getAllCategory")
public List<ccCategory> getAllCategory() {
// public List<String> getAllCategory() {
System.out.println("***** Call : API getAllCategory() ******");
List<ccCategory> cCategory = categoryRepository.findAll();
return cCategory;
}
Angular Code :
<label class="control-label">Category: </label>
<select [(ngModel)]="listAllCategory" name="xxcategory" class="form-control" required>
<option *ngFor="let xxcategory of listAllCategory" [value]="xxcategory.catID">
{{xxcategory.categoryName}}
</option>
</select>
Problem :
Drop Down populating all the table value but I want only the UNIQUE value like only one time catID , categoryName.
You have to add a variable to keep the selected element in your select and then change your [(ngModel)]="listAllCategory" with [(ngModel)]="selectedCategory"
Related
I have question on my Salesforce WebService and Apex Code.
In a relationship, we have one Notice and multiple attachments in my salesforce. But I don't know how to fix below requirements:
when "GET" webservices incoming thru specific URL API, it supposed to return with JSON format
JSON Format should {Notice1 : attach1{link},attach2{link} , etc }
#RestResource(urlMapping='/API/V1/notice/*')
global with sharing class API_Notice {
#HttpGet(UrlMapping='/API/V1/notice/all')
global static List<String> getNotice(){
Set<Id> NoticeIds = new Set<Id>();
Set<Id> VersionIds = new Set<Id>();
String compares;
List<String> returnJSON = new List<String>();
List<Notice__c> reConts = [select Id, ClosingDate__c ,Name, Contents__c from notice__c];
Map<Id,Notice__c> addMap = new Map <Id,Notice__c>();
Map<Map<Id,Notice__c>,Map<Id,contentdistribution>> addsMap = new Map<Map<Id,Notice__c>,Map<Id,contentdistribution>>();
//SET NOTICE ID
if(!reConts.isEmpty()){
for(Notice__c nc : reConts){
NoticeIds.add(nc.Id);
addMap.put(nc.id,nc);
}
}
//GET public Image URL
if(!NoticeIds.isEmpty()){
Map<Id,ContentDocumentLink> contentMap = new Map<Id,ContentDocumentLink>([
select contentDocumentid,LinkedEntityId from ContentDocumentLink where LinkedEntityId IN:NoticeIds
]);
for(ContentDocumentLink Key : contentMap.values()){
VersionIds.add(Key.ContentDocumentId);
}
if(!VersionIds.isEmpty()){
Map<Id, contentdistribution> cdb = new Map <Id, contentdistribution> ([
select DistributionPublicUrl from contentdistribution where contentDocumentid IN:VersionIds
]);
addsMap.put(addMap,cdb);
}
}
return null;
}
}
I have an IQueryable from the database, which I map to view model like this:
IQueryable<ItemList> itemsList = query.Select(x =>
new ItemList()
{
Phone = x.Phone,
Email = x.Email,
Fax = x.Fax,
State = x.StateId.HasValue ? new GenericBox() { Text = x.State.Name , Value = x.State.Id } : null,
Type = x.Type,
ChildItems = x.Contact.ChildItems.OrderBy(a => a.Order).Select(a => new GenericBox() { Text = a.Child.FirstName + " " + a.Child.LastName, Value = a.ChildId })
});
The GenericBox class is like this:
public class GenericBox
{
public string Text { get; set; }
public Guid Value { get; set; }
}
Then I transform this IQueryable to pure SQL and execute it with a SqlCommand.
The problem lies in the properties State and ChildItems.
I need to set alias for State properties Text and Value. Because IQueryable set them in the SQL with random generated names:
SELECT
[Project3].[Id] AS [Id1],
[Project3].[Phone] AS [Phone],
[Project3].[Email] AS [Email],
[Project3].[Fax] AS [Fax],
[Project3].[C2] AS [C2],
[Project3].[Name1] AS [Name1],
[Project3].[StateId] AS [StateId],
[Project3].[Type] AS [Type],
[Project3].[C5] AS [C3],
[Project3].[C3] AS [C4],
[Project3].[AgentId] AS [AgentId]
As you can see in the SELECT Name1 is for the State.Text from my class and C4 is for ChildItem.Text.
I need in the SELECT the alias for column Name1 to be Text for example. And the alias for Column C4 I want to be again Text.
I don't really know what words or terms I would search. I have also read the documentation in laravel 5.7, https://laravel.com/docs/5.7/eloquent-relationships#many-to-many-polymorphic-relations.
But still I couldn't find the thing that I want.
The result that I am expecting is this in MySQL:
SELECT id as product_id, (SELECT name FROM products WHERE id = transactions.product_id), created_at FROM transactions WHERE user_id = 1
This is the result of the mysql query:
I already have a model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Transactions extends Model
{
protected $table = 'transactions';
protected $fillable = [
'user_id', 'product_id'
];
public function product()
{
return $this->hasOne('App\Products')->select('name');
}
}
?>
Then in my controller:
public function transactions()
{
$transactions = new Transactions::where('user_id',Auth::id())->product;
return view('transactions', ['transactions' => $transactions]);
}
You should use belongsTo() relation. Transaction belongs to one product, product has many transactions.
Also, you can (or better should) rename model to a singlular. Then you don't need to use protected $table.
It is not necessarily to select only name.
Transaction model:
namespace App;
use Illuminate\Database\Eloquent\Model;
class Transaction extends Model
{
protected $fillable = ['user_id', 'product_id'];
public function product()
{
return $this->belongsTo('App\Product');
}
}
Controller:
public function transactions()
{
$transactions = Transaction::with('product')
->where('user_id', Auth::id())
->get();
return view('transactions', ['transactions' => $transactions]);
}
View:
#foreach($transactions as $transaction)
echo $transaction->product_id; //attribute product_id of transaction
echo $transaction->product->id; //attribute id of product
echo $transaction->product->name; //attribute name of product
#endforeach
in my database i save users tag in table
the table structure is
Table Name : User
Id Name Tags
1 Jack White,Yellow,Green
2 smith Yellow,Green
3 smith Blank
....
the condition is:
string[] tags = {"Yellow","Green"};
I hope can get the data from database,so this is my lambda:
unitOfWork.Repository<User>().find(x=>!x.Any(x.Tag.......);
the sql like:
Select * from Users Where Tags not in('Yellow','Green')
but the tags in database is long string with ","
If you have big data, this is not a good solution But you can after you select all data.
var result = db.Users.ToList()
.Where(i => i.Tags.Split(',').Any(t => tags.Contains(t))).ToList();
I think, normalize your schema looks like better.
Other option:
You can use SqlQuery
class Users
{
public int Id { get; set; }
public string Name { get; set; }
public string Tags { get; set; }
}
string[] tags = {"Yellow","Green"};
var whereClause = String.Join(" OR ", tags.Select(i => String.Format("Tags LIKE %{0}%", i));
var query = String.Format(#"
SELECT
*
FROM
Users
Where
{0}
", whereClause);
var result = dbContext.Database.SqlQuery<Users>(query);
Query looks like:
SELECT
*
FROM
Users
Where
Tags LIKE %Yellow% OR Tags LIKE %Green%
I am looking on selecting a small group of random contacts from a specific view. The records are in that view if their campaign status is set to sent. I have created an apex class that I think would work, however I am trying make this class a controller and build a visual force page. I am knew to salesforce and apex. After doing some research i think i will have to use getters and setters to call the information. My apex class is
public class MyController {
Integer count = [SELECT COUNT() FROM Contact];
Integer rand = Math.floor(Math.random() * count).intValue();
Set<Id> contactIds = new Set<Id>();{
for(CampaignMember cm : [Select Id, ContactId from CampaignMember where Status = 'To be Called' and Campaign.Name = '2014/15 Mascot Data']){
contactIds.add(cm.ContactId);
List<String> orderBys = new List<String>{'Email Asc','Email Desc','Lastname Asc','Firstname Desc','LastModifiedDate Desc','LastModifiedDate Asc','CreatedDate Asc','CreatedDate Desc','Id Asc','Id Desc'};
String orderBy = orderBys.get(Math.mod(rand,orderBys.size()));
List<Contact> contacts = (List<Contact>)Database.query('Select Name From Contact where ID in :contactIds Order By ' + orderBy + ' Limit 5 OFFSET :rand');
}
}
}
Many thanks
Try the following code:
Visualforce Page:
<apex:page controller="MyController">
<apex:form>
<apex:pageblock id="pb" title="Contact Information">
<apex:commandButton value="Get Random Contacts" action="{!getContacts}" rerender="randomContacts"/>
<apex:outputPanel id="randomContacts">
<apex:pageblock>
<apex:PageBlockTable value="{!contacts}" var="item">
<apex:column headerValue="Contact Name" value="{!item.Name}"/>
--display columns you wish to show.
</apex:PageBlockTable>
</apex:pageblock>
</apex:outputPanel>
</apex:pageBlock>
</apex:form>
</apex:page>
Apex Class:
public class MyController
{
public List<Contact> contacts{get;set;}
public MyController()
{
getContacts();
}
public void getContacts()
{
Integer count = [SELECT COUNT() FROM Contact];
Integer rand = Math.floor(Math.random() * count).intValue();
Set<Id> contactIds = new Set<Id>();
contacts = new List<Contact>();
for(CampaignMember cm : [Select Id, ContactId from CampaignMember where Status = 'To be Called' and Campaign.Name = '2014/15 Mascot Data'])
{
contactIds.add(cm.ContactId);
}
List<String> orderBys = new List<String>{'Email Asc','Email Desc','Lastname Asc','Firstname Desc','LastModifiedDate Desc','LastModifiedDate Asc','CreatedDate Asc','CreatedDate Desc','Id Asc','Id Desc'};
String orderBy = orderBys.get(Math.mod(rand,orderBys.size()));
contacts = Database.query('Select Name From Contact where ID in :contactIds Order By ' + orderBy + ' Limit 100 OFFSET :rand');
}
}
First time it load data when page loaded and click on the button to get next random contacts.
Hope it helps you.