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.
Related
I have two tables in my database, one for "sales" informations and the other for "sale content" (items). What is the best method to present this using the laravel models? For example, is it better to create a model for each table or can we only use one?
A Model for each table - you cannot use one Model for multiple tables.
Laravel tries to infer the table name from the Model name based on lowercase pluralisation - so if your Model is called Sale it will presume that the table is called "sales". If your table is something else, you defined the table in the Model using :
protected $table = "online_sales";
Then you will need to define the relationships between the two models - the documentation is here : https://laravel.com/docs/8.x/eloquent-relationships
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.
Ok, lets say you have two tables: Order and OrderLine and for some reason they do not have a foreign key relationship in the database (it's an example, live with it). Now, you want to join these two tables using Entity Framework and you cook up something like this:
using (var model = new Model())
{
var orders = from order in model.Order
join orderline in model.OrderLine on order.Id equals orderline.OrderId into orderlines
from ol in orderlines.DefaultIfEmpty()
select new {order = order, orderlines = orderlines};
}
Now, the above will produce orders and orderlines, left-joined and all, but it has numerous issues:
It's plain ugly
It returns an anonymous type
It returns multiple instances of the same order and I you have to do Distinct() on the client side because orders.Distinct() fails.
What I am looking for is a solution which is:
Pretty
Returns a statically well-known type instead of the anonymous type (I tried to project the query result, but I got into problems with the OrderLines)
Runs Distinct on the server side
Anyone?
Even if the database tables do not have a foreign key relationship setup, you can configure Entity Framework as if they do.
Add an OrderDetails navigation property to your Order class and then just query Orders.
so the story is very simple.
I have one table called Products and another Called categories. In addition, i have another table called ProductCategories that hold the relationship of catetories to their corresponding products (i.e, the table has two columns, ProductId, ColumnId).
For some reason, after adding all those table to my entity model, i don't have "Access" to it, hence i can do myentityModel.ProductCategories, so i could relational items between those two tables.
And yes, the ProductCategores table is added as "Association" to the entity model. i don't really understand that.
EDIT:
I do see that as part of creating new "Product" i can pass EntityCollection of "Category". So i do query from my entity model for a list of the matching categories that the user selected (on the webpage). so for example, i get (after query the model), an Objectset of "Category". However, i encountered two issues:
the 'AddObject' accept only EntityCollection, hence i need to re-create a set and then add all the objects from the ObjectSet to the entityCollection, in this process i need to detach it from the previous model and add it to the new collection. if not, i get an exception.
when i do the SaveChanges, i see that i get an exception that it was actually trying to Create new Category rather than adding new ProductCategory. again, am i missing something here?
Thanks.
This sounds like a Many-to-Many relationship. In your entity model, you don't need to declare the join table as a separate entity. Instead, you configure the relationship between the Products and the Categories as a Many-to-Many and add metadata about the join table. In Hibernate, you would have:
#ManyToMany(targetEntity=Categories.class, cascade={CascadeType.ALL}, fetch = FetchType.LAZY)
#JoinTable(name="tb_products_categories",
joinColumns=#JoinColumn(name="category_id"),
inverseJoinColumns=#JoinColumn(name="product_id")
)
#IndexColumn(name="join_id")
public List<Categories> getCategories() {
return categories;
}
When you query, the ORM layer takes care of determining SQL and traversing table joins.
I have 3 normalised tables consisting of Employees, Departments and EmployeesToDepartments. I wish to be able to assign an Employee to one or more Department, hence the link table (EmployeesToDepartments). I can successfully query the database and extract the full hierarchy of entities via the Navigation properties using
this.ObjectContext.Employees.Include("EmployeesToDepartments").Include("EmployeesToDepartments.Department")
plus the [Include] attribute in the metadata, thus allowing me to access the Departments for a given Employee. Upon trying to remove a link between an [Employee] and [Department] in the [EmployeesToDepartments] table I was given a Foreign Key Constrain error.
I have simplified my model to include just one navigation property between [Employees] and [EmployeesToDepartments]. A Foreign Key constraint between[Employees].[ID] and [EmployeesToDepartments].[IDEmployee] was preventing me from updating the EmployeesToDepartments table. With this removed via a Relationship setting I can now update the table. I can now execute the following code
foreach (var rel in _employee.EmployeesToDepartments)
{
_employee.EmployeesToDepartments.Remove(rel);
}
_domainContext.SubmitChanges();
without error.
I was expecting to see the entries in the RelEmployeesToDepartments with the IDEmployee to have been deleted. What I see in the table are the value 0 where the IDEmployee previously was.
Is it possible to force a DELETE statement to be issued? Am I misunderstanding the basic concepts here?
Any help would be much appreciated.
Removing entities in navigation property only breaks the link between entities. You have to delete from the EntitySet to achive what you want.
ex)
myDomainContext.EmployeeDepartments.Remove(employeeDepartmentToRemove);
myDomainContext.SubmitChanges();