laravel 如何从laravel 5中的两个相关表中获取数据?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31907563/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to get data from two related tables in laravel 5?
提问by Jonathan Solorzano
I've got two models Employees and Departments, i would like to get the all the data from the employee including it's department, something like this:
我有两个模型员工和部门,我想从员工那里获取所有数据,包括其部门,如下所示:
SELECT e.Firstname, e.Surname, e.Age, d.Name as Department FROM Employees as e INNER JOIN Departments as d ON e.Department = d.ID;
The result of that is:
结果是:
------------------------------------------
| Firstname | Surname | Age | Department |
------------------------------------------
| John | Doe | 25 | Finance |
How could i get the same result in Laravel 5?
我怎么能在 Laravel 5 中得到相同的结果?
I know that i can get all the data of a model like this:
我知道我可以像这样获取模型的所有数据:
$data = Employees::all();
But i need the Department column as the value of the parent table.
但我需要 Department 列作为父表的值。
Using the Query Builderit look like this
使用查询生成器它看起来像这样
DB::table('Employees')
->join('Departments', 'Employees.Department', '=', 'Departments.ID')
->select('Employees.Firstname', 'Employees.Surname', 'Employees.Age', 'Departments.Name')
->get();
And using Eloquent it look like this
使用 Eloquent 看起来像这样
Model
模型
public function department()
{
return $this->belongsTo('App\Departments','Department','ID');
}
Controller
控制器
$data->employees = Employees::with('department')->get();
Using the Query builder i can pass the data through @include
and access to it like this:
使用查询构建器,我可以@include
像这样传递数据并访问它:
app.blade.php
应用程序.blade.php
@include('Club.index.employees',['employees'=>$data->employees])
employees.blade.php
员工.blade.php
@foreach($employees as $employee)
@include('Club.index.member',['employee'=>$employee])
@endforeach
member.blade.php
会员.blade.php
<h3>{{ $employee->Firstname }}</h3>
<p class="member-surname">{{ $employee->Surname }}</p>
...
And it works, but when i use Eloquent it doesn't display the fields from the parent like Departments.Name
in this case, i don't know if i'm missing something when calling it in the view.
Also i would like to know how could i use aliases for the table columns.
它可以工作,但是当我使用 Eloquent 时,它不会像Departments.Name
在这种情况下那样显示来自父级的字段,我不知道在视图中调用它时是否遗漏了什么。另外我想知道如何为表列使用别名。
回答by Khan Shahrukh
In your model Employee create a function department
在您的模型 Employee 中创建一个职能部门
public function department()
{
return $this->hasMany('App\Department');
}
Then in your controller do like this
然后在你的控制器中这样做
$results = Employee::with('department')->get();
This is how you will get all the departments of the employee, but make sure both the table are related on a foreign key basis
这是您获取员工所有部门的方式,但要确保两个表在外键基础上相关