Querying with Eloquent - Achieve Join - laravel

How to select records from db from a situation like below using eloquent
Tables:
Employee Table [ id,name]
Address Table [id,address_line1,employee_id,city_id]
City Table [id,name]
A Query like below does only return city id, but i need the city name as well
$employee = Employee::with('address')->get();
And My Employee Model have relationship as
public function address(){
$this->hasMany('address');
}
How to achieve the desired result so that the output of the query should give me city name from city table, based on the id from address table, without running new query for each city id to get names

Related

How to access multiple model data from an eloquent call

I currently have a product table with the following columns:
id, product_name, product_type, description
I also have three more tables:
medias, attributes, coatings
each of those tables has an id, name, description, img
Each product created din the product table will have multiple, medias, attributes and coatings. To address this I created a table product_relations which contains the columns:
id, product_id, media_id, attribute_id, coating_id
From here I thought I would make a call to product_relations with the product_id and then pull each record so I can access the data. However I'm stuck on how I would do this as an eloquent relationship. Would I do separate has many's in my Product_Relation model like so:
public function media()
{
return $this->hasMany('App\Media');
}
public function attributes()
{
return $this->hasMany('App\Attributes');
}
etc? Or is there a simpler way to build this to access all that at once?

Laravel Relationships: 3 Models

I have a problem with laravel relationships.
I have 3 models:
City —(hasMany) —>Clinic—(hasMany) —>Stock
Stock —(belongsTo) —>Clinic —(belongsTo) —>City
I need get all cities which has stocks, looks like «Stock->cities». I can write sql-query:
SELECT ct.id, ct.name
FROM CfgCity as ct
RIGHT JOIN lr_clinics AS cl ON(ct.id=cl.city_id)
RIGHT JOIN lr_clinic_stocks AS st ON(cl.id=st.clinic_id)
WHERE st.deleted_at IS NULL
GROUP BY ct.id
But I want decision in laravel-orm, because it’s more readable and I don’t need write names of rows and tables. Is it possible?
Thanks.
From your question it is clear that city has relation with clinic and clinic has relation with stock that means city has relation with stock through clinic. That you can define it using laravel relationship.
City Model
class City extends Model {
public function clinics(){
return $this->hasMany(Clinic::class);
}
public function stocks(){
return $this->hasManyThrough(Stock::class, Clinic::class);
}
}
Fetch data
$cities = City::whereHas('stocks')->get();
For details you can check https://laravel.com/docs/5.6/eloquent-relationships#has-many-through

Get foreign key table property MVC

I have a student model with a departmentID foreign key. And the Department model has two property, ID and code. I cannot access the department code by the departmentID from student table. And yes I have this,
public virtual Department Department { get; set; }
in my student model. I tried this,
student.Department.code
but it returns null. I have no idea what I am missing. And I need the value to generate a student reg no. before saving student data. like this,
student.RegCode = student.ID + student.Department.Code;
first you had to call a variable to match the id and receive Department object
var code = db.Departments.Where(u => u.ID == student.DepartmentID).FirstOrDefault();
once you have your object data on a variable, you can access all its properties. like below,
student.RegCode = code.code+ "-" + student.ID;

Eloquent - Two Relationships In One?

I've been getting along slowly but surely with Laravel / Eloquent, but am now stumped:
entries Table:
id
user_id
group_id
content
users Table
id
faculty_id
name
group Table:
id
name
faculty Table
id
name
So entries are related to users and groups, and users are related to faculties - I've set up the basic relationships without a problem, and this enables me to find all entries by users from a certain faculty:
Faculty Model:
public function entries()
{
return $this->hasManyThrough('Entry','User');
}
Controller:
Faculty::find(Faculty-ID-here)->entries;
However, I now need to find entries by users that are from a certain faculty AND from a certain group, and I don't know how to write this combination this in Eloquent.
Hope that makes sense! Any suggestions?
Something like:
Entries::whereHas('user', function($q) {
$q->where('faculty_id', $facultyID);
})
->where('group_id', $groupID)
->get();
Assuming you have set up your 'user' relationship.

How to do "nested" eager loading in Entity Framework?

Scenario:
Employee: EmployeeId (PK) DepartmentId_FK (FK) Name and other fields
Department: DepartmentId (PK) CompanyId_FK (FK) Name and other fields
Company: CompanyId (PK) Name and other fields
How can I build a linq query that can join the three tables and returns EmployeeName, DepartmentName and CompanyName?
the following syntax does not work because there is no Navigation Property names Company on Employee.cs.
var model = DataContext.Employee
.Include("Employer")
.Include("Company");
What is the correct way to do this?
Try this :
var data = DataContext.Employees.Include("Department").Include("Department.Company");
But use this with caution as eager loading can hurt back if there is large amount of data.

Resources