How to use with() on model instance - eloquent

I have model relationship as such Manager > Employee > Orders > Orderlines
I want to get all the Orderlines under a Manager, so I go:
$manager = Manager::find(1);
$surprise = $manager->with('employees.orders.orderlines')->get();
I expect $surprise to have only data from 1 manager, but it is fetching all data from all managers. What is the correct usage such that I only get orderlines from the Manager model instance?

Related

Entity Framework: referencing entities from a model of another context

I have two Db contexts: CustomersDb which maps to a Customers database, and OrdersDb, which maps to Orders database.
I have a model for each context
Customer
{
Id,
Name
}
Order
{
Id,
Virtual Customer
}
How how do I reference the Customer entity from the Orders model correctly? When I seed these DBs, EF creates a Customers table in the Orders database, and obviously, I don't want that

How i can achieve relational data using Hibernate Search?

I am using JPARepository, I chose Hibernate Search for implementing search functionality.
Here is link : http://hibernate.org/search/documentation/getting-started/
Using an EntityManager (JPA) to rebuild an index
FullTextEntityManager ftem = Search.getFullTextEntityManager(entityManager);
ftem.createIndexer().startAndWait();
Suppose I have Two Entity classes Company.java & Employee.java.
Employees(e_id) saved under Company(c_id) and relation stored in another table "company_employee".
I want to implement search on only those employees(not all employees of other companies) which are associated with company account.
for eg: select e_id from company_employee where c_id = ?
Now assume i getting 3 employees of company and want to fetch the all record of these 3 employees and not others.
You fetch company and not employee like this :
QueryBuilder qb = fullTextEntityManager.getSearchFactory()
.buildQueryBuilder().forEntity(Company.class).get();
In your lucene query :
luceneQuery = queryBuilder.keyword().wildcard().onFields("employees.employeeName").matching("m*").createQuery()
Employees is the field annotatted with #IndexedEmbedded.
public class Company {
...
#IndexedEmbedded
private List<Employee> employees;
...
}
You will get a company with only its employees and not all the employees. (I don't know if you have to use eager fetch or not)
Is that what you are looking for ?

Attaching an related entity to new entity, without retrieving from database

I've just started working with Web API this week, and I'm struggling with something which I think should be quite simple, but haven't been able to find the answer for yet. Perhaps I'm searching using the wrong terms.
One of the calls to the API passes through a GUID. I need to create a new entity (using Entity Framework) and set one of the relations to this newly passed in GUID. This GUID is the ID of a different entity in the database.
I'm struggling to attach the entity via the relation without fetching the whole entity too.
For example,
public void DoWork(IList<Guid> userGuids)
{
Order order = new Order() // This is an entity
{
CreateDate = DateTime.Now,
CreatedBy = "Me",
Items = (from i in this.Model.Items
where i.Id == userGuid
select i).ToList<Item>();
}
Model.Orders.Add(order);
Model.SaveAll();
}
In the above, I have to do a database call to attach the Item entities to the Order. Is there not a way around this? Seems very redundant to retrieve the whole entity objects when I only require their IDs (which I already have anyway!)!
One solution is stub entities as asked here: Create new EF object with foreign key reference without loading whole rereference object
Link to the source blog referenced: http://blogs.msdn.com/b/alexj/archive/2009/06/19/tip-26-how-to-avoid-database-queries-using-stub-entities.aspx
Snip from the blog - to be applied to your situation:
Category category = new Category { ID = 5};
ctx.AttachTo(“Categories”,category);
Product product = new Product {
Name = “Bovril”,
Category = category
};
ctx.AddToProducts(product);
ctx.SaveChanges();
This way (in the example) the Product is saved without ever loading the Category object.

EF Code First - Many to Many Database to 1 to Many Domain

I would like to be able to have a domain model with a different representation to the database model we are currently using.
At the moment we have a many to many relationship between a schedule and a line item, so a schedule has many line items and each line item can be reused across many schedules. In our code base though we only ever need to be concerned with a specific schedule, so the scenarios would be adding existing line items to a schedule or adding a new line item to a schedule, and alternately, getting a collection of line items for a given schedule.
In the database however we store the ordering of the line items on the mapping table. What I would like to do is represent this relationship in the doman model as a 1 to many relationship between schedule and line item and the line item domain model has an integer order property.
I can't seem to find any way to easily flatten this model using EF Code First and be able to put the property onto line item.
Essentially the database is:
Schedule
-Id
ScheduleLineItem
-ScheduleId
-LineItemId
-Order
LineItem
-Id
and the domain model I would like to use is:
Schedule
-Id
-List<LineItem>
LineItem
-Id
-Order
There is no way to flatten it in the mapping. You must map the model in the same way as database is designed and you can expose custom non mapped properties simulating non existing one-to-many relation.
For example:
public class Schedule
{
public int Id { get; set; }
public virtual ICollection<ScheduleLineItem> ScheduledItems { get; set; } // This is necessary for EF
public IEnumerable<LineItem> LineItems
{
return ScheduledItems.OrderBy(i => i.Order).Select(i => i.LineItem);
}
}

Using the entity framework to add existing entities to a collection on a newly created entity

I am using the Entity framework to create a new order. The order contains a collection of contacts, a many to many relationship. I want to add a reference to an existing contact on the order on creation of the order. Both Order and Contact a Entity Objects.
Order order = new Order();
//set details on order
Contact contact = new Contact();
EntityKey contactKey =
new EntityKey("OrderDetails.Contact",
"contact_id", contact.Key.Id);
contact.EntityKey = contactKey;
contact.contact_id = contact.Key.Id;
order.Contact.Attach(contact); // throws an exception!
OrderDetails ordTable = new OrderDetails();
ordTable.AddToOrder(order);
int result = orgTable.SaveChanges();
When I go to attach, this exception is thrown:
"Attach is not a valid operation when the source object associated with this related end is in an added, deleted, or detached state. Objects loaded using the NoTracking merge option are always detached."
I know I'm probably missing a step or not fully understanding how the entity framework handles many-to-many relationships.
"Attach" is not allowed because you haven't saved the order yet. Calling "Add" tells Entity Framework that you want to insert a new contact. So you are left with only one option. You need to load the contact.
Here's the fastest way to do that:
OrderDetails context = new OrderDetails();
Contact contact = context.GetObjectByKey(new EntityKey("OrderDetails.Contact", "contact_id", existingContactId));
order.Contact.Add(contact);
If Order has a property Contact, then you can do:
order.Contact.Add(contact);
I would suggest making the property called Contacts rather than Contact, though.