Variable in filter query in Jaydata - database

I have a string which I need to pass in filter query of Jaydata.Kindly guide..
Here is my following code:
var string = ((id=4 || id>6)&& (Name contains 'a'));
mydb.Document.filter(function(result){
return result.str;
}).toArray(function(abc){
console.log(abc);
});
Here mydb is sQlite db instance name and Document is table name.
Error comes when I use result.str as str is not the field name of the table.
How can I do this.

your filter is not correct, also you can pass parameter with referring the second parameter, like this
mydb.Document.filter(function(result){
return result.str == this.foo;
}, { foo: 'bar'}).toArray(function(abc){
of course, instead of 'bar' you can pass any value

Related

unexpected result in a query in laravel

I’m a beginner in Laravel but have a problem at first. I wrote this query and I’m waiting for Sonya Bins as result but unexpectedly I see ["Sonya Bins"]. what’s the problem?
Route::get('products', function () {
$articles=DB::table('users')->where('id','2')->get()->pluck('name');
return view('products',compact('articles'));
});
pluck will return array if you want to get only single value then use value
// will return array
$articles=DB::table('users')->where('id','2')->get()->pluck('name');
//will return string
$articles=DB::table('users')->where('id','2')->value('name');
// output Sonya Bins
here is an example from the documentation:
if you don't even need an entire row, you may extract a single value from a record using the value method. This method will return the value of the column directly:
$email = DB::table('users')->where('name', 'John')->value('email');
Read more about it here
Hope it helps.
Thanks
pluck() used to return a String before Laravel 5.1, but now it returns an array.
The alternative for that behavior now is value()
Try this:
Route::get('products', function () {
$articles=DB::table('users')->where('id','2')->get()->value('name');
return view('products',compact('articles'));
});
I think it's easier to use the Model + find function + value function.
Route::get('products', function () {
$articles = User::find(2)->value('name');
return view('products',compact('articles'));
});
pluck will return the collection.
I think id is your primary key.
You can just get the first record, and call its attribute's name:
DB::table('users')->where('id','2')->first()->name;
or
DB::table('users')->find(2)->name;
First thing is that you used invalid name for what you pass to view - you don't pass articles but user name.
Second thing is that you use get method to get results instead of first (or find) - you probably expect there is only single user with id = 2.
So to sum up you should use:
$userName = DB::table('users')->find(2)->name;
return view('products',compact('userName'));
Of course above code is for case when you are 100% sure there is user with id = 2 in database. If it might happen there won't be such user, you should use construction like this:
$userName = optional(DB::table('users')->find(2))->name;
($userName will be null if there is no such record)
or
$userName = optional(DB::table('users')->find(2))->name ?? 'No user';
in case you want to use custom string.

Database.getQueryLocator return wrong data

I am very puzzled on the result returned by the Database.getQueryLocator().
global Database.QueryLocator start(Database.BatchableContext BC) {
string query = 'Select Label, Batch_Name__c, SObject_Name__c, External_system__c from Batch_Upload_Config__mdt where Is_Active__c = true';
System.debug(query);
return Database.getQueryLocator(query);
}
In the Query Editor, I entered the exact query and did get the correct data back. However when running the batch, instead of returning the records with 'Is_Active__c = true', it returns the records with 'Is_Active__c = false'.
Any pointers will be appreciated.
Looks like this is related to query on custom metadata types. When I changed to use custom object, I was able to get the correct result using Database.getQueryLocator().

String Jsonarray in android [duplicate]

So, I get some JSON values from the server but I don't know if there will be a particular field or not.
So like:
{ "regatta_name":"ProbaRegatta",
"country":"Congo",
"status":"invited"
}
And sometimes, there will be an extra field like:
{ "regatta_name":"ProbaRegatta",
"country":"Congo",
"status":"invited",
"club":"somevalue"
}
I would like to check if the field named "club" exists so that at parsing I won't get
org.json.JSONException: No value for club
JSONObject class has a method named "has":
http://developer.android.com/reference/org/json/JSONObject.html#has(java.lang.String)
Returns true if this object has a mapping for name. The mapping may be NULL.
You can check this way where 'HAS' - Returns true if this object has a mapping for name. The mapping may be NULL.
if (json.has("status")) {
String status = json.getString("status"));
}
if (json.has("club")) {
String club = json.getString("club"));
}
You can also check using 'isNull' - Returns true if this object has no
mapping for name or if it has a mapping whose value is NULL.
if (!json.isNull("club"))
String club = json.getString("club"));
you could JSONObject#has, providing the key as input and check if the method returns true or false. You could also
use optString instead of getString:
Returns the value mapped by name if it exists, coercing it if
necessary. Returns the empty string if no such mapping exists
just before read key check it like before read
JSONObject json_obj=new JSONObject(yourjsonstr);
if(!json_obj.isNull("club"))
{
//it's contain value to be read operation
}
else
{
//it's not contain key club or isnull so do this operation here
}
isNull function definition
Returns true if this object has no mapping for name or
if it has a mapping whose value is NULL.
official documentation below link for isNull function
http://developer.android.com/reference/org/json/JSONObject.html#isNull(java.lang.String)
You can use has
public boolean has(String key)
Determine if the JSONObject contains a specific key.
Example
JSONObject JsonObj = new JSONObject(Your_API_STRING); //JSONObject is an unordered collection of name/value pairs
if (JsonObj.has("address")) {
//Checking address Key Present or not
String get_address = JsonObj .getString("address"); // Present Key
}
else {
//Do Your Staff
}
A better way, instead of using a conditional like:
if (json.has("club")) {
String club = json.getString("club"));
}
is to simply use the existing method optString(), like this:
String club = json.optString("club);
the optString("key") method will return an empty String if the key does not exist and won't, therefore, throw you an exception.
Try this:
let json=yourJson
if(json.hasOwnProperty(yourKey)){
value=json[yourKey]
}
Json has a method called containsKey().
You can use it to check if a certain key is contained in the Json set.
File jsonInputFile = new File("jsonFile.json");
InputStream is = new FileInputStream(jsonInputFile);
JsonReader reader = Json.createReader(is);
JsonObject frameObj = reader.readObject();
reader.close();
if frameObj.containsKey("person") {
//Do stuff
}
Try this
if(!jsonObj.isNull("club")){
jsonObj.getString("club");
}
I used hasOwnProperty('club')
var myobj = { "regatta_name":"ProbaRegatta",
"country":"Congo",
"status":"invited"
};
if ( myobj.hasOwnProperty("club"))
// do something with club (will be false with above data)
var data = myobj.club;
if ( myobj.hasOwnProperty("status"))
// do something with the status field. (will be true with above ..)
var data = myobj.status;
works in all current browsers.
You can try this to check wether the key exists or not:
JSONObject object = new JSONObject(jsonfile);
if (object.containskey("key")) {
object.get("key");
//etc. etc.
}
I am just adding another thing, In case you just want to check whether anything is created in JSONObject or not you can use length(), because by default when JSONObject is initialized and no key is inserted, it just has empty braces {} and using has(String key) doesn't make any sense.
So you can directly write if (jsonObject.length() > 0) and do your things.
Happy learning!
You can use the JsonNode#hasNonNull(String fieldName), it mix the has method and the verification if it is a null value or not

Passing a full-text search parameter using Dapper.net

Consider this simple query which use full text searching on the Keywords field:
DECLARE #searchTerm VARCHAR(500) = 'painted'
SELECT * FROM StockCatalogueItems
WHERE (CONTAINS(KeyWords, #searchTerm))
This works as expected, but I need to do the same using a Dapper.net parameterised query. When using stored procedures, I create the full text parameter like this: "\"painted*\""
But using the same approach this doesn't work using dapper. No results are returned. This is the line in the query where I use the parameter:
AND (CONTAINS(KeyWords, #search))
and it's passed to the query like so:
return _context.Database.Connection.Query<StockProfileMatrix>(basequery, new
{
search = searchTerm
}
I can only assume that dapper is sanitising the string somehow, removing quotes perhaps?
Any ideas?
This works for me. However the tech stack am working on is .net core RTM and "Dapper": "1.50.0-rc3",
_dbConnection.QueryAsync<Guid>(#"select br.Id from Brand br where CONTAINS(br.Text,#Name)",new {Name = $"\"*{name}*\""}))
For completeness, I'll answer the question. The query syntax is correct, but the way in which the full-text parameter is created was obviously not. I created an extension method that formats the parameter:
public static string ToFullText(this string str)
{
string searchTerm = null;
if (!string.IsNullOrEmpty(str))
{
string[] keywords = str.Trim().Split(null);
foreach (var keyword in keywords)
{
searchTerm += string.Format("\"{0}*\" AND ", keyword);
}
if (searchTerm != null)
searchTerm = searchTerm.Substring(0, searchTerm.LastIndexOf(" AND "));
}
return searchTerm;
}
Then I call the method when I pass the parameter in to the dapper query:
_context.Database.Connection.Query<dynamic>(query, new
{
search = filter.SearchTerm.ToFullText()
});

Dapper Results(Dapper Row) with Bracket Notation

According to the Dapper documentation, you can get a dynamic list back from dapper using below code :
var rows = connection.Query("select 1 A, 2 B union all select 3, 4");
((int)rows[0].A)
.IsEqualTo(1);
((int)rows[0].B)
.IsEqualTo(2);
((int)rows[1].A)
.IsEqualTo(3);
((int)rows[1].B)
.IsEqualTo(4);
What is however the use of dynamic if you have to know the field names and datatypes of the fields.
If I have :
var result = Db.Query("Select * from Data.Tables");
I want to be able to do the following :
Get a list of the field names and data types returned.
Iterate over it using the field names and get back data in the following ways :
result.Fields
["Id", "Description"]
result[0].values
[1, "This is the description"]
This would allow me to get
result[0].["Id"].Value
which will give results 1 and be of type e.g. Int 32
result[0].["Id"].Type --- what datattype is the value returned
result[0].["Description"]
which will give results "This is the description" and will be of type string.
I see there is a results[0].table which has a dapperrow object with an array of the fieldnames and there is also a result.values which is an object[2] with the values in it, but it can not be accessed. If I add a watch to the drilled down column name, I can get the id. The automatically created watch is :
(new System.Collections.Generic.Mscorlib_CollectionDebugView<Dapper.SqlMapper.DapperRow>(result as System.Collections.Generic.List<Dapper.SqlMapper.DapperRow>)).Items[0].table.FieldNames[0] "Id" string
So I should be able to get result[0].Items[0].table.FieldNames[0] and get "Id" back.
You can cast each row to an IDictionary<string, object>, which should provide access to the names and the values. We don't explicitly track the types currently - we simply don't have a need to. If that isn't enough, consider using the dapper method that returns an IDataReader - this will provide access to the raw data, while still allowing convenient call / parameterization syntax.
For example:
var rows = ...
foreach(IDictionary<string, object> row in rows) {
Console.WriteLine("row:");
foreach(var pair in row) {
Console.WriteLine(" {0} = {1}", pair.Key, pair.Value);
}
}

Resources