Kohana ORM Relationships - kohana

I have a couple of tables and have defined relationships for them.
{Table Department} {Table Unit} {Table Branch}
A Department can have more than one branch, a branch can only belong to one department. I need to be able to get the department name, departmentid, branchname
Branch has an instance of departmentid in it.
How do I pull this in one ORM call?
class Model_Admin_Departments extends ORM
{
protected $_has_many = array('branches' => array ());
class Model_Admin_Branches extends ORM
{
protected $_belongs_to = array('departments ' => array());
I have also created the foreign key constraints on the db side with action cascade on delete. Could this cause problems or that is fine?

Assuming you have the right relationships declared you should be able to use the with(...) method on your ORM object.

Related

how can i fill controller with data - SQL Function in Entity Framework?

i have create an sql function in my database that take to Date params and get data from 5 tables.
after that add it to project as entity framework from database and the code generated is:
[DbFunction("Dr_EmploEntities", "SelectEmployee")]
public virtual IQueryable SelectEmployee(Nullable frm_date, Nullable to_date)
{
var frm_dateParameter = frm_date.HasValue ?
new ObjectParameter("frm_date", frm_date) :
new ObjectParameter("frm_date", typeof(DateTime));
var to_dateParameter = to_date.HasValue ?
new ObjectParameter("to_date", to_date) :
new ObjectParameter("to_date", typeof(DateTime));
return ((IObjectContextAdapter)this).ObjectContext.CreateQuery("[Dr_EmploEntities].[SelectEmployee](#frm_date, #to_date)", frm_dateParameter, to_dateParameter);
}
public DbSet SelectEmployee_Result { get; set; }
as you see i have now "SelectEmployee_Result" that don't take any params, and "SelectEmployee" that take two date params.
after that i have create an controller for "SelectEmployee_Result" class.
after that i run my project Index View that working with "SelectEmployee_Result" class give me err:
"The type 'SelectEmployee_Result' is mapped as a complex type. The Set method, DbSet objects, and DbEntityEntry objects can only be used with entity types, not complex types."
and i make breakpoint and see that "SelectEmployee_Result" has no data so i change the Index Code in controller and fill "SelectEmployee" with two date params
and when run got same err msg too.
so how can i fill "SelectEmployee_Result" from the beginning with data between two dates to let me use it in all views ?
all what i need here is view data i got i edit before saving it in database Like using DataTable but i need to do that from Entity with sql function
and what is difference between "SelectEmployee" that is my function name and that is need two params and "SelectEmployee_Result"?

Entity Framework Model First 1:0..1 Relationship

I created the following model in the Entity Framework 5 Model Designer in Visual Studio 2012:
Then I generated the database from the model, which resulted in the following tables in my database:
Please help me understand why Entity Framework is generating a one-to-many relationship for a one-to-zero-or-one association.
Update #1
Furthermore, if I change the association from 1:0..1 to 1:1 like this:
Then not only is there still no one-to-one relationship in the database, but now the one-to-many relationship is flipped around, which seems even more weird to me:
Update #2
In response to Mystere Man's comment and answer, the structure I'm expecting to see in SQL Server, which is a valid 1:0..1 relationship is as follows:
Furthermore, I am able to get this working exactly as intended with the following Code First fluent mapping:
public class UserMap : EntityTypeConfiguration<User>
{
public UserMap()
{
ToTable("Users");
HasKey(t => t.UserId);
Property(t => t.UserId)
.HasColumnName("UserId");
Property(t => t.Name)
.HasColumnName("Name")
.IsRequired()
.HasMaxLength(50);
Property(t => t.EmailAddress)
.HasColumnName("EmailAddress")
.IsRequired()
.HasMaxLength(254);
Property(t => t.CreatedDateTime)
.HasColumnName("CreatedDateTime");
HasOptional(t => t.Subscription)
.WithRequired(t => t.User);
}
}
public class SubscriptionMap : EntityTypeConfiguration<Subscription>
{
public SubscriptionMap()
{
ToTable("Subscriptions");
HasKey(t => t.SubscriptionId);
Property(t => t.SubscriptionId)
.HasColumnName("SubscriptionId");
Property(t => t.TypeValue)
.HasColumnName("TypeValue");
Property(t => t.CreatedDateTime)
.HasColumnName("CreatedDateTime");
Property(t => t.ExpiresDateTime)
.HasColumnName("ExpiresDateTime");
HasRequired(t => t.User)
.WithOptional(t => t.Subscription);
}
}
So, I know it's possible to achieve this behavior with Code First Entity Framework. My question is why it's not possible to do it with the Model First approach.
What's going on here and why?
Thanks!
SQL does not have a way to define a true 1:1 or 1:0..1 data model, except when both entities have the same primary key. Even so, you can't have a 1:1 because you can't insert records into more than one table in a single statement, so the data model has to allow 1:0..1 by virtue of there being a intermediate state where one record will exist without the other.
The only way to do this in SQL is to do exactly what EF is doing here, create a 1:*, and then impose constraints ensure uniqueness (such as a Unique Constraint). However, EF doesn't support constraints (you would have to create them manually) so it's possible to insert more than one record and violate your model.
EDIT:
Since you've clarified that you're talking about Model First, and that you are looking for a shared primary key, then here's what you have to do.
Right click on the Association, and create a referential constraint between Subscription and User. This will then cause EF to generate the 1:0..1 relationship you are looking for.

Fluent NHibernate - Multiple collections in the same table

Im working on rebuilding a clients software and they want to keep their database as unmodified as possible.
I got a table where they collect users and orders for different companies, no biggie there but the twist is they do it for multiple entities.
for example the table looks like this:
ID
UserID
Index
CompanyID
Type
lets say they got entities like Project and Workflow, then the Type column would be 'P' for projects and 'W' for workflows. So on a ID is the ID of a Project or Workflow Identity. UserID is always a foreign key to a User entity and Index is the order that the user is used when this Project/Workflow is used. And CompanyID is what company owns project or workflow entity.
I have tried to search google for this but i came up with nothing.
What i want is on a Template entity map two collections say StandardProjectUsers and StandardWorkflowUsers and they should collect them from correct entities with a user and index for current company.
Is this at all possible with fluent nhibernate ?
A nice article on how to do it: http://www.philliphaydon.com/2011/08/fluent-nhibernate-table-inheritance-discriminators/
You are looking at a table-per-hierarchy strategy.
In a nutshell you use:
public class BaseClassMap : ClassMap<BaseClass>
{
public BaseClassMap()
{
DiscriminateSubClassesOnColumn("Type");
...
}
}
public class WorkflowMap : SubclassMap<Workflow>
{
public WorkflowMap()
{
DiscriminatorValue("W");
...
}
}
public class ProjectMap : SubclassMap<Project>
{
public ProjectMap()
{
DiscriminatorValue("P");
...
}
}

Kohana 3.1 ORM: Trying to build subsequent one-to-many relationships

I have a MySQL table structure that looks like this:
Countries -> Countries_Regions (FK: country_id) -> Countries_Regions_Cities (FK: region_id)
So, there's a one-to-many relationship between country and region, and there's a one-to-many relationship between region and city
I tried to link them with the following classes:
class Model_Country extends ORM {
protected $_has_many = array('regions' => array("model" => "Countries_Region"));
}
class Model_Countries_Region extends ORM {
protected $_has_many = array('cities' => array("model" => "Countries_Regions_City"));
protected $_belongs_to = array('country' => array("model" => "Country"));
}
class Model_Countries_Regions_City extends ORM {
protected $_belongs_to = array('region' => array("model" => "Countries_Region"));
}
Everything goes fine if I try to find all the regions with
$country = ORM::factory("country", 1);
$region = $country->regions->find_all();
But when I try to find all the cities bottom-up, with
$country = ORM::factory("country", 1);
$city = $country->regions->cities->find_all();
It does recognize the city property in region, but it returns an empty row with all the city values set to NULL.
I feel like I'm missing something very obvious, but I can't figure out what it is. Please help me.
It does recognize the city property in region
Because $country->regions returns an ORM object with prepared WHERE statements, not a list of regions. If you call $country->regions->find_all(), you will get an array of regions, but after that you can access to their cities only through foreach loop.
There is a simple way, I think. Just add a country_id field to a City model and define a Belong_To relationship. So you will be able to use $country->cities or $city->country without loading regions.

Saving Parent and children

I have a couple of tables in my schema with PK and FK relationships. I have created the DAL using the SubSonic generator. If I create a new parent and its children, how should I save both? Separately or in one shot?
e.g.
Parent.Save();
ChildCollection.SaveAll();
I tried the above, but it does not work because ChildCollection does not have its parent's ID. Is it that I have to assign parent IDs for each child myself or is there an option to save it all in one shot?
Assumption: That your Primary Keys are auto generated by your Data Base. If so, what you will need to do first is Save() the parent and then populate the ParentID property in each of the objects in your ChildrenCollection. Once you have done that, you will be able to Save() your ChildrenCollection.
Parent.Save();
ChildCollection.ForEach(x => x.ParentID = Parent.ParentID);
ChildCollection.SaveAll();
You can use partial classes with custom overload of save function to provide the desired functionality.
public partial class Class1
{
public void Save(bool childern)
{
Save();
if (childern)
{
//based on primary/foreign key SubSonic provides
//methods to fetch child collections related to
//this (primary key) table.
ChildernCollection col = Childerns();
col.SaveAll();
}
}
}

Resources