I'm having difficulty ordering the CRUD rows by a related value. In my main case I want to order jobs by the weight of their associated status
Job (table)->status_id ---> Status (table)->weight
I've got belongsTo and hasMany relationships setup correctly and add / edit etc, works well, I just can't figure out how to set the $this->crud->orderBy()
It's no different than sorting any Laravel model by its relation. And I think the standard way is to use Laravel's eager loading for that:
$this->crud->query = $this->crud->query->with(['status' => function ($query) {
$query->orderBy('weight', 'desc');
}])->get();
Hope it helps!
Related
In Yii2, am I able to include two models (active records) in one search model and display them in a gridview?
For example, I have two tables, "customers", and "customer_contacts".
In my search model I am using Customers as my main model, while I wish to "left join" to CustomerContacts, and eventually display the Customers.name and CustomerContacts.phoneNumber in the gridview (in dataProvider).
Can someone please guide me on this.
Thank.
Option 1:
In the customer model add this function:
Public function getCustomerContact(){
Return $this-> hasOne( CustomerContact::className,[customer_id,id]);
}
Then in your grid view you can easily reference the contact as follows:
customerContact.name
Note that this will only work if there is a one to one relationship between the tables
Option 2: (faster but more challenges)
In the data provider, use a query rather than a model ie $query = new \yii\db\Query();
You can then do all joins etc in the data provider. It is much faster but it requires a little more know-how
you can do this by applying left-join in searchModel as following
$query = Customers::find();
$query->joinWith('customer-contact');
And also make hasOne relation with CustomerContact in Customer.php
I am new to EF so please bear with me. I am using Entity Framework with an existing database in which the relationships are not defined.
Using EF, I am able to produce the model, but obviously the 'navigational properties' are not working. Is there a way I can specify the mapping between the entities?
For example, in my Product entity, I have a field CategoryID_fk (maps to Category entity). But since the relationships are not defined, I cannot load a Category while loading a Product entity.
Can someone guide me in this regard?
I do understand that it would be preferable to refactor our database but I am unable to do that now. Thanks in advance.
This link is very useful.http://www.entityframeworktutorial.net/
I think field names are not suitable conventions.Try to change field name as CategoryId or Category_CategoryId .I think it will work
Yes, you can do a group join. Basically you will retrieve Products and Category in separate queries and take an approach as indicated in this answer.
Something along these lines:
var productCategoryList = products.GroupJoin
(
categories,
p=> p.productId,
c=> c.CategoryId,
(p, c) => new ProductCategory
{
//Create your Product Category model here
}
).AsEnumerable();
Is it possible to include a computed field in an EF entity? Example, lets say I have a shop selling products, and the products are grouped into categories.
When the list of categories is displayed for editing to the administrator of the shop I wish to list the number of products in each category as part of the list.
In NHibernate I would use a formula e.g.
<property name="Products" formula="dbo.Category_NumProducts(id)" />
I can't work out if something similar is possible for EF. I know I could make a category view and map this to a second entity but that seems wrong as its almost a complete duplication.
EDIT: If this isn't possible in EF, then what is the best way to accomplish this?
Unfortunately if your Category table doesn't have this as computed column you will not be able to map it without creating second entity - it leads to database view, defining query in EDMX or perhaps Query view in EDMX (but Query view may not work because you require aggregate function to be computed).
Edit:
IMHO the simplest solution (and also the best) is simply creating a ViewModel (some non mapped class) and use projection in Linq query:
var query = from c in context.Categories
where ...
select new CategoryView {
Id = c.Id,
Name = c.Name,
...
Products = c.Products.Count()
};
Lets say that I have a class called Stock and which has a virtual ICollection Prices, which is a historical set of prices.
If you fetch a stock and after the stock is materialized you query the Prices but apply a filter like mystock.Prices.OrderByDescending(px => px.Date).First(), EF internally loads all the prices and then it applies the filters used, since prices could be a large collection, I would really like to see EF just load the price that matched my where criteria. Basically applying the filtering at the server end rather than client side.
Is it possible to do this?
Thanks
It's possible, but this way only works if you can assume Prices is really an EntityCollection rather than some other class that also happens to implement ICollection. I'm not sure if this is true in all supported EF scenarios. The function to use is EntityCollection's CreateSourceQuery function.
((EntityCollection<Price>)stock.Prices).CreateSourceQuery().OrderByDescending(price => price.Date).First();
If that doesn't work for you, another possibility might be to go back to the context, and query from there:
(from price in context.Prices
where price.StockId == stockId
orderby price.Date descending
select price).First();
Greetings,
Considering the Northwind sample tables Customers, Orders, and OrderDetails I would like to eager load the related entities corresponding to the tables mentioned above and yet I need ot order the child entities on the database before fetching entities.
Basic case:
var someQueryable = from customer in northwindContext.Customers.Include("Orders.OrderDetails")
select customer;
but I also need to sort Orders and OrderDetails on the database side (before fetching those entities into memory) with respect to some random column on those tables. Is it possible without some projection, like it is in T-SQL? It doesn't matter whether the solution uses e-SQL or LINQ to Entities. I searched the web but I wasn't satisfied with the answers I found since they mainly involve projecting data to some anonymous type and then re-query that anonymous type to get the child entities in the order you like. Also using CreateSourceQuery() doesn't seem to be an option for me since I need to get the data as it is on the database side, with eager loading but just by ordering child entities. That is I want to do the "ORDER BY" before executing any query and then fetch the entities in the order I'd like. Thanks in advance for any guidance. As a personal note, please excuse the direct language since I am kinda pissed at Microsoft for releasing the EF in such an immature shape even compared to Linq to SQL (which they seem to be getting away slowly). I hope this EF thingie will get much better and without significant bugs in the release version of .NET FX 4.0.
Actually I have Tip that addresses exactly this issue.
Sorting of related entities is not 'supported', but using the projection approach Craig shows AND relying on something called 'Relationship Fixup' you can get something very similar working:
If you do this:
var projection = from c in ctx.Customers
select new {
Customer = c,
Orders = c.Orders.OrderByDescending(
o => o.OrderDate
)
};
foreach(var anon in projection )
{
anon.Orders //is sorted (because of the projection)
anon.Customer.Orders // is sorted too! because of relationship fixup
}
Which means if you do this:
var customers = projection.AsEnumerable().Select(x => x.Customer);
you will have customers that have sorted orders!
See the tip for more info.
Hope this helps
Alex
You are confusing two different problems. The first is how to materialize entities in the database, the second is how to retrieve an ordered list. The EntityCollection type is not an ordered list. In your example, customer.Orders is an EntityCollection.
On the other hand, if you want to get a list in a particular order, you can certainly do that; it just can't be in a property of type EntityCollection. For example:
from c in northwindContext.Customers
orderby c.SomeField
select new {
Name = c.Name,
Orders = from o in c.Orders
orderby c.SomeField
select new {
SomeField = c.SomeField
}
}
Note that there is no call to Include. Because I am projecting, it is unnecessary.
The Entity Framework may not work in the way you expect, coming from a LINQ to SQL background, but it does work. Be careful about condemning it before you understand it; deciding that it doesn't work will prevent you from learning how it does work.
Thank you both. I understand that I can use projection to achieve what I wanted but I thought there might be an easy way to do it since in T-SQL world it's perfectly possible with a few nested queries (or joins) and order bys. On the other hand seperation of concerns sounds reasonable and we are in the entity domain now so I will use the way you two both recommended though I have to admit this is easier and cleaner to achieve in LINQ to SQL by using AssociateWith.
Kind regards.