If I have a query that returns multiple results, how do I get a single element from the selection?
e.g.
r.db("test").table("things") // returns an array of things. I want one of them
Using limit(1) is not what I want because that returns an array.
Rethink DB supports getting the nth element so the query should be:
r.db("test").table("things").nth(0)
In the event that there are no elements, the above will fail with:
Index out of bounds: 0
The solution to this is to return a default object (null in my case) if no element exists.
r.db("test").table("things").nth(0).default(null)
Related
I have a long Linq query and I'm trying to take one data in any index of that query.
My query is :
public IEnumerable<WebFairField> WebFairFieldForFair(Guid ID,int index)
{
return TradeTurkDBContext.WebFairField.Where(x => x.DataGuidID==ID)
.Include(x => x.Category)
.ThenInclude(x=>x.MainCategory).AsSplitQuery()
//
.Include(x=>x.FairSponsors)
.ThenInclude(x=>x.Company)
.ThenInclude(x=>x.FileRepos).AsSplitQuery()
//
.Include(x=>x.WebFairHalls.Take(1).ElementAt(index)) //Thats the point where i stuck*
.ThenInclude(x=>x.HallSeatingOrders)
.ThenInclude(x=>x.Company)
.ThenInclude(x=>x.FileRepos).AsSplitQuery()
//
.Include(x=>x.HallExpertComments).AsSplitQuery()
.Include(x=>x.Products).AsSplitQuery()
.Include(x=>x.FairSponsors).AsSplitQuery()
.AsNoTrackingWithIdentityResolution()
.ToList();
}
when I do that it gives me an error : Collection navigation access can be filtered by composing Where, OrderBy,ThenBy,Skip or Take operations.
I know I have to sort that data but I don't know how to do it. Can anyone show me how should I sort my data of that query ?
Thanks for any suggestion!!
The error
As you have mentioned, the line of
.Include(x=>x.WebFairHalls.Take(1).ElementAt(index)) //Thats the point where i stuck*
is causing the error. Basically you Take the first element and then try to call ElementAt. This is a problem technically, because you need to convert your collection to IEnumerable in order to be able to call ElementAt.
It is also a logical error, since if you take a single element, then it does not make sense to try and call ElementAt for it.
Skip
As Guru Strong pointed out, you can Skip, as Skip(index - 1).Take(1) which skips the first index - 1 elements and then takes the next one, which is the index'th element.
Sort
If you need to sort, call OrderBy. If you need several sorting criteria, then use ThenBy.
$row->sub_category[0]->name
when i checked other questions, i could see that there is option to access the first and last elements, but is there a way to access an element based in array index value.
I need to get the n-th item in a hasmany relationship (where you know n) and would getting it on its own direactly without foreach loop (without loading other relationship elements ).
If you want the N-th item of a relationship without loading all other elements you can (probably) use query:
$nthSubcategory = $row->sub_category()->skip($n-1)->first()
If it doesn't exist then $nthSubcategory will end up being null
I have a table user which contains an array Employee which stores the names ,i need to retrieve the last element of the array.
Could not figure out.Tried with count but count gives value =1 but there are three elements in an array
r.table("user")("Employee").count()
I need count actual elements in Employee array which is 3.Please help.Thanks
If you don't call .count on a specific document's field, it will return the count of the sequence of documents. In your request, 1 as a result actually means there is one document in the table.
You need to loop over each document to fetch the last name for each document, and you can fetch it directly using .nth:
r.table("user").map(function(document) {
return document.merge({lastName: document("Employee").nth(-1)});
// or, if you like complicated stuff
return {
id: document('id'),
lastName: document("Employee").nth(
document("Employee").count().sub(1)
)
};
});
I want to get alternative products pictures.
dd($alternativeProduct->pictures);
When die and dump i get this result.
I need to get only the picture which is main. If main equals to 1. It is main picture.
When I write
dd($alternativeProduct->pictures->where('main', 1))
I got an empty array.
Here is my relation with Product and Picture relation
public function pictures(){
return $this->hasMany('App\Models\ProductPicture');
}
What can i do ?
The where method in a collection has three parameters: $key, $value and $strict, the last one defaults to true if not passed when calling the method. When $strict is true the comparison is done via === which does not do type coercion, meaning "1" === 1 is false.
From your dump data, I can see that "main" => "1" which means it's a string and you're passing an integer 1 to the where method, resulting in what I described above as a false condition and returning an empty result set. You can fix that by disabling strict comparison:
$alternativeProduct->pictures->where('main', 1, false);
// or the equivalent helper whereLoose
$alternativeProduct->pictures->whereLoose('main', 1);
Or passing a string as the value:
$alternativeProduct->pictures->where('main', "1");
That being said, if that's the only place you're using that collection in that request's context, I suggest that you filter the results at the database level, not after they are fetched, like so:
$alternativeProduct->pictures()->where('main', 1)->get();
Accessing the relations as a method ->pictures(), instead of as a property ->pictures, will return a Query Builder instance that allows you to add conditions to the database query and only fetch the actual items you need from the database, instead of fetching them all and filtering them out afterwards.
You may want to use whereLoose instead:
dd($alternativeProduct->pictures->whereLoose('main', 1))
From the Laravel docs:
The where method uses strict comparisons when checking item values. Use the whereLoose method to filter using "loose" comparisons.
I don't know the difference between FirstOrDefault and SingleOrDefault. When should I use the first and when should I use the second?
FirstOrDefault() is for when zero or more results are expected to be present in the input collection and the call returns the first item if there are multiple results, Default if none.
SingleOrDefault() is for when zero or one result is expected in the input collection and the call returns the one result if exactly one result is present, Default if no results and exception if more than one result.
SingleOrDefault will throw a "Sequence contains more than one element" exception if more than one item exists.
firstordefault it will take number of rows but will just return first one of it if it is
null it can handle the exception
First it will take number of rows but will just return first one of it if it is
null it will throw the exception
singleordefault it will take only one row but will return it can handle exceptions if it is null
single it will take only one row but will return it & cannot handle exceptions
If your result set returns 0 records:
SingleOrDefault returns the default value for the type (e.g. default for int is 0)
FirstOrDefault returns the default value for the type
If you result set returns 1 record:
SingleOrDefault returns that record
FirstOrDefault returns that record
If your result set returns many records:
SingleOrDefault throws an exception
FirstOrDefault returns the first record
Conclusion:
If you want an exception to be thrown if the result set contains many records, use SingleOrDefault.
If you always want 1 record no matter what the result set contains, use FirstOrDefault