Trying to sort my table. The numbers are category_id and they are not sorted by number (1 and 2 are at the bottom of the table), I want to order them.
Controller:
public function fetchcategory(){
$all_categories = HmsBbrCategory::all();
return response()->json([
'all_categories'=>$all_categories,
]);
}
When I try the code below, I get 500 internal server error in my console:
$all_categories = HmsBbrCategory::orderBy('category_id', 'ASC')->all();
What am I doing wrong witht the orderBy code?
Just for reference to know difference between all() and get()
all()
Its a static method so you cant execute additional queries.Only option you have in all() method is you can select columns.
public static function all($columns = ['*'])
{
return static::query()->get(
is_array($columns) ? $columns : func_get_args()
);
}
If we see implementation of that static all() method. Internally it calls get() method
1.all() accept columns as array. Default set to * ,it means all columns selected.
2.Inside of that method ,we can see get() called. So after get we cant call any query operations so its throwing error
get() is Eloquent builder \Illuminate\Database\Eloquent\Builder
Simply you have to update this line
$all_categories = HmsBbrCategory::orderBy('category_id', 'ASC')->all();
into
$all_categories = HmsBbrCategory::orderBy('category_id', 'ASC')->get();
then you will get your result .
Related
I am using Apache Ignite as the back-end data store in a SpringBoot Application.
I have a requirement where I need to get all the entities whose name matches one of the names from a set of names.
Hence i am trying to get it implemented using a #Query configuration and a method named findAllByName(Iterable<String> names)as below:
Here on the Query, I am trying to use the 'IN' clause and want to pass an array of names as an input to the 'IN' clause.
#RepositoryConfig(cacheName = "Category")
public interface CategoryRepository extends IgniteRepository<Category, Long>
{
List<Category> findByName(String name);
#Query("SELECT * FROM Category WHERE name IN ( ? )")
Iterable<Category> findAllByName(Iterable<String> names); // this method always returns empty list .
}
In this the method findAllByName always returns empty list, even when ignite has Categories for which the name field matches the data passed in the query.
I am unable to figure out if there is a problem with the Syntax or the query of the method signature or the parameters.
Please try using String[] names instead for supplying parameters.
UPDATE: I have just checked the source, and we don't have tests for such scenario. It means that you're on uncharted territory even if it is somehow possible to get to work.
Otherwise looks unsupported currently.
I know your question is more specific to Spring Data Ignite feature. However, as an alternate, you can achieve it using the SqlQuery abstraction of Ignite.
You will form your query like this. I have pasted the sample below with custom sql function inSet that you will write. Also, the below tells how this is used in your sql.
IgniteCache<String, MyRecord> cache = this.ignite
.cache(this.environment.getProperty(Cache.CACHE_NAME));
String sql = "from “my-ignite-cache”.MyRecord WHERE
MyRecord.city=? AND inSet(?, MyRecord.flight)"
SqlQuery<String, MyRecord> sqlQuery = new SqlQuery<>(MyRecord.class,
sql);
sqlQuery.setArgs(MyCity, [Flight1, Flight2 ] );
QueryCursor<Entry<String, MyRecord>> resultCursor = cache.query(sqlQuery);
You can iterate the result cursor to do something meaningful from the extracted data.
resultCursor.forEach(e -> {
MyRecord record = e.getValue();
// do something with result
});
Below is the Ignite Custom Sql function which is used in the above Query - this will help in replicating the IN clause feature.
#QuerySqlFunction
public static boolean inSet(List<String> filterParamArgIds, String id) {
return filterParamArgIds.contains(id);
}
And finally, as a reference MyRecord referred above can be defined something like this.
public class MyRecord implements Serializable {
#QuerySqlField(name = "city", index = true)
private String city;
#QuerySqlField(name = "flight", index = true)
private String flight;
}
I have a field in my database with duplicates. I want to use it in a dropdown list, which has to return distinct data.
Here is the method that I created to do this:
public IEnumerable<SelectListItem> GetBranches(string username)
{
using (var objData = new BranchEntities())
{
IEnumerable<SelectListItem> objdataresult = objData.ABC_USER.Select(c => new SelectListItem
{
Value = c.BRANCH_CODE.ToString(),
Text = c.BRANCH_CODE
}).Distinct(new Reuseablecomp.SelectListItemComparer());
return objdataresult;
}
}
Here is the class I am using:
public static class Reuseablecomp
{
public class SelectListItemComparer : IEqualityComparer<SelectListItem>
{
public bool Equals(SelectListItem x, SelectListItem y)
{
return x.Text == y.Text && x.Value == y.Value;
}
public int GetHashCode(SelectListItem item)
{
int hashText = item.Text == null ? 0 : item.Text.GetHashCode();
int hashValue = item.Value == null ? 0 : item.Value.GetHashCode();
return hashText ^ hashValue;
}
}
}
Nothing is returned and I get the error below. When I try a basic query without Distinct, everything works fine.
{"The operation cannot be completed because the DbContext has been disposed."}
System.Exception {System.InvalidOperationException}
Inner exception = null
How can I return distinct data for my dropdown?
Technically, your problem can be solved simply by appending .ToList() after your Distinct(...) call. The problem is that queries are evaluated JIT (just in time). In other words, until the actual data the query represents is needed, the query is not actually sent to the database. Calling ToList is one such thing that requires the actual data, and therefore will cause the query to be evaluated immediately.
However, the root cause of your problem is that you are doing this within a using statement. When the method exits, the query has not yet been evaluated, but you have now disposed of your context. Therefore, when it comes time to actually evaluate that query, there's no context to do it with and you get that exception. You should really never use a database context in conjuction with using. It's just a recipe for disaster. Your context should ideally be request-scoped and you should use dependency injection to feed it to whatever objects or methods need it.
Also, for what it's worth, you can simply move your Distinct call to before your Select and you won't need a custom IEqualityComparer any more. For example:
var objdataresult = objData.ABC_USER.Distinct().Select(c => new SelectListItem
{
Value = c.BRANCH_CODE.ToString(),
Text = c.BRANCH_CODE
});
Order of ops does matter here. Calling Distinct first includes it as part of the query to the database, but calling it after, as you're doing, runs it on the in-memory collection, once evaluated. The latter requires, then, custom logic to determine what constitutes distinct items in an IEnumerable<SelectListItem>, which is obviously not necessary for the database query version.
Simplified Model:
public class GolfCourseDetailsPart : ContentPart<GolfCourseDetailsRecord>
{
public bool ShowInHomePage {... //Get and Set using Retrieve and Store methods
}
Simplified Migrations:
ContentDefinitionManager.AlterTypeDefinition("GolfCourse", gc => gc
//...
.WithPart(typeof(GolfCourseDetailsPart).Name)
);
I need to filter all items of type "GolfCourse" to get only the ones that have ShowInHomePage set to true.
Filter:
I have created a filter implementing the IFilterProvider interface and it returns all the GolfCourse content items but I couldn't get to filter by ShowInHomePage yet:
private void ApplyFilter(FilterContext context)
{
context.Query = context.Query.Join(x=>x.ContentPartRecord(typeof(GolfCourseDetailsRecord)));
}
How could I get to filter by the property ShowInHomePage??
You are almost there, the only part missing is the .Where clause. In a HQL query it looks like this:
private void ApplyFilter(FilterContext context)
{
context.Query = context
.Query
.Join(x => x.ContentPartRecord(typeof(GolfCourseDetailsRecord)))
.Where(x => x.ContentPartRecord<GolfCourseDetailsRecord>(), g => g.Eq("ShowInHomePage", true));
}
Is there any reason you want to create an IFilterProvider?
Those will be only useful if you want to have a customized filter available for query projections.
If you simply want to get filtered data programmatically then I would use Query method of ContentManager.
Here is a set of samples on how querying Orchard, I think it will be more useful for you than if I simply put here the query you need: https://orchardtrainingdemo.codeplex.com/SourceControl/latest#Controllers/ContentsAdminController.cs
I have a problem on yii model, ive been told to use the generateAttributeLabel() on the model, but i tried to use it on the way i thought it would work but it doesnt. This is my code
public function generateAttributeLabel($variable = file_get_contents('protected\column.txt'))
{
return $variable;
}
public function attributeLabels()
{
return array(
'id' => 'ID',
'parametro_id' => 'Parametro',
);
}
There are some columns that are being generated automatically and i thought to save their names into a file and its saved as example like (index, par, tolt, sircer). Thats why the file_get_contents(), but i get an error:
Parse error: syntax error, unexpected '(', expecting ')'.
so i really dont know and i need this to make checkboxlist with the attributes of each column thats going to be saved as y or n, if someone could tell me how to use this with checkboxlist would be appretiated.
the content file is this
lololo,
for now it has 1 element, but will be adding more each time a column is created
You can't use a function return value as a default value in a function declaration, you will need to set that up in the function itself
public function generateAttributeLabel($variable = null){
if($variable){
$variable = file_get_contents($variable);
}
return $variable;
}
Can I filter out results from an arrayCollection in Doctrine 2 while using lazy loading? For example,
// users = ArrayCollection with User entities containing an "active" property
$customer->users->filter('active' => TRUE)->first()
It's unclear for me how the filter method is actually used.
Doctrine now has Criteria which offers a single API for filtering collections with SQL and in PHP, depending on the context.
https://www.doctrine-project.org/projects/doctrine-orm/en/latest/reference/working-with-associations.html#filtering-collections
Update
This will achieve the result in the accepted answer, without getting everything from the database.
use Doctrine\Common\Collections\Criteria;
/**
* #ORM\Entity
*/
class Member {
// ...
public function getCommentsFiltered($ids) {
$criteria = Criteria::create()->where(Criteria::expr()->in("id", $ids));
return $this->getComments()->matching($criteria);
}
}
The Boris Guéry answer's at this post, may help you:
Doctrine 2, query inside entities
$idsToFilter = array(1,2,3,4);
$member->getComments()->filter(
function($entry) use ($idsToFilter) {
return in_array($entry->getId(), $idsToFilter);
}
);
Your use case would be :
$ArrayCollectionOfActiveUsers = $customer->users->filter(function($user) {
return $user->getActive() === TRUE;
});
if you add ->first() you'll get only the first entry returned, which is not what you want.
# Sjwdavies
You need to put () around the variable you pass to USE. You can also shorten as in_array return's a boolean already:
$member->getComments()->filter( function($entry) use ($idsToFilter) {
return in_array($entry->getId(), $idsToFilter);
});
The following code will resolve your need:
//$customer = ArrayCollection of customers;
$customer->getUsers()->filter(
function (User $user) {
return $user->getActive() === true;
}
);
The Collection#filter method really does eager load all members.
Filtering at the SQL level will be added in doctrine 2.3.