retrieve full data from foreign table with eloquent - eloquent

I've been reading some answers to similar questions here on the site, it seems everyone is trying to use a low level approach. The question is, shouldn't laravel and eloquent make it easy to solve stuff like that?
If I have a table with ids to two foreign tables, exmple item_id foreign of table items and item_type_id foreign of table item_types. How can I retrieve and join the data from these two tables directly instead of manually specifiying the id to look at in those foreign table and stuff?
Shouldn't eloquent have something like "get data from foreign table given the ids that you found in pivot table and spit out the joined data" ?

Laravel Eloquent: Relationships
I believe you should refer eloquent relationships. It would help you to fetch datas from related datatables.
For Ex: We can have 2 to 3 three table Users, Groups & user_group(pivot table)
The user_group would have the relation between each user and various groups.
In User Model
class User extends Eloquent
{
public function groups()
{
return $this->belongsToMany('Group', 'user_group', 'user_id', 'group_id');
}
}
In Group Model
class Group extends Eloquent
{
public function users()
{
return $this->belongsToMany('Group', 'user_group', 'group_id', 'user_id');
}
}
Now you can fetch a user and his relation with groups likewise:
$user_groups = User::find($user_id)->groups;
And to fetch the members of a group likewise:
$group_members = Group::find($group_id)->users;
This code basically does the join in the backend.
Refer docs for deeper understanding.
Hope this would get you started.

Related

How to use joinwith in yii2 framework

I have created a curd called 'Status' and it is working properly. I have created a new Model(with table) called relation(id, status_id, user_id).
Now I want to join relation table to Status while showing records with some custom condition.
How to do that?
To make connection between two tables with foreign key create function in model Relation like this.
public function getStatus()
{
return $this->hasOne(Status::className(),['id'=>'status_id']);
}
To access value of status from relation model object, you can like this.
$relation->status->name_of_attribute;
$relation one object from Relation model.

Adding DateTime field to many-to-many EF Code First relationship

I am using EF 6 Code-First, table per type, and I have two concrete classes Group and User. Group has a navigation property Members which contains a collection of User. I have mapped this many-to-many relationship in EF using Fluent syntax:
modelBuilder.Entity<Group>
.HasMany<User>(g => g.Members)
.WithMany(u => u.Groups);
I would like to be able to say when a member has joined a group so that I can query for, say, the newest member(s). I am not sure of how this is best accomplished within the framework.
I see the following options:
Create and use an audit table (ie GroupMembershipAudit consisting of Group, User, join/unjoin, and DateTime
Add a column to the autogenerated many-to-many table between User and Group
Is there anything within EF to facilitate this sort of storage of many-to-many historical info like this / append columns to the many-to-many relationship?
Add a column to the autogenerated many-to-many table between User and
Group
That is not possible - auto-generated junction tables can contain only keys (that is called Pure Join Table). According to Working with Many-to-Many Data Relationships article: If the join table contains fields that are not keys, the table is not a PJT and therefore Entity Framework cannot create a direct-navigation (many-to-many) association between the tables. (Join tables with non-key fields are also known as join tables with payload.)
Create and use an audit table (ie GroupMembershipAudit consisting of
Group, User, join/unjoin, and DateTime
Actually you should create GroupMembershipAudit entity. With Code First table will be generated, you don't need to create it manually.

JPA Multiple relationships on one field in an entity

I am a beginner to using JPA 2.0 and databases in general and I was just confused about a few concepts.
So I have a total of 3 tables. One is the UserTable, which contains all the information about my user. It has a primary key field called user_Id. My other two tables are ExercisesTable and FoodIntakeTable, and they each have a foreign key field called user_Id to reference the user_Id in my UserTable. I want a one-to-many relationship from my user_Id table to each of the two tables so I can find pull out exercise information or food information for a user.
Pretty much like this:
FoodIntakeTable <-> UserTable <-> ExercisesTable
I need a bidirectional mapping from UserTable to FoodIntakeTable and also a bidirectional mapping from UserTable to ExercisesTable from the field user_Id.
The problem is, when I try to write my code like this in my Usertable class:
#OneToMany(mappedBy="ExercisesTable.userId")
#OneToMany(mappedBy="FoodIntakeTable.userId")
public long userId;
It's illegal because I can't have two #OneToMany annotations on the same field. I think it's supposed to be legal in a normal relational database and I'm just confused about how you translate this into JPA. I'm very new to the whole concept of databases and entities in general, so any help would be appreciated.
In JPA you can directly reference entity objects instead of the ids that they are mapped by. Try something like this:
You should have an entity type for each of your tables, say Exercise for ExercisesTable, FoodIntake for FoodIntakeTable, and User for your UserTable.
Then your User entity is the owning side of the relationships, having one field per relationship like this:
#OneToMany(mappedBy=...)
private List<Exercise> exercises;
#OneToMany(mappedBy=...)
private List<FoodIntake> foodIntakes;

How to design many-to-many relationship in JPA entities?

I am trying to understand what would be the better way to design 2 entities which has many-to-many relationship? In database there will be a connecting table between these two entities. But do i have to follow the same approach while creating my entities?
For example: User to User group
A user may belong to many group and a group may contain many user.
In relational database I will have 3 table like User, User2Group, Group
So when I am creating my JPA entities, should I have 3 entities for 3 table or just 2 entities by providing the proper annotation(#ManytoMany).
Since I am new to JPA, I am trying to understand good and bad side from following point of view:
Performance
Code maintenance
Thanks, you input will be greatly appreciated.
No, you don't need to map the join table as an entity. Just use the ManyToMany annotation:
public class User {
...
#ManyToMany
private Set<Group> groups;
}
public class Group {
...
#ManyToMany(mappedBy = "groups")
private Set<User> users;
}
You would only need to map the join table as an entity if it was not a pure join table, i.e. if it had additional information like, for example, the date when the user entered in the group.
The mapping has little incidence on the performance. What is important is how you use and query the entities, and how the database is designed (indices, etc.)

Entity Framework v1 Modelling Many-to-Many Lookup Table Relationship

I have the following database tables:
Table1: UserUserIdUsername
Table2: RoleRoleIdRolename
Table3: UserRoleUserIdRoleId
A User can have many Roles and a Role can have many Users.
When I model this with EF, I get a User entity with a list of UserRole entities. What I want is a User with a list of Role entities.
Is there a way to model this or query via LINQ to return a User entity and the Role entities they belong to?
Thanks
Dirk
If you model a many-to-many relation, the table in the middle will not appear in your conceptual model. (i.e. you will not have a class "UserRole" derived from "EntityObject")
If you use the EF wizard, ensure that your table "UserRole" only have these two Fields and no others. Also ensure, that you have created the foreign key constraints on both of the fields. if you have, then the wizard will create a proper many-to-many relation.
The query then probably looks something like
using(MyObjectContext context = new MyObjectContext(someParameters)){
var theUser = (from user in context.UserSet
where user.UserId = XY
select user).First();
theUser.Roles.Load();
}