如何从连接表中选择列:laravel eloquent
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45437607/
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 select columns from joined tables: laravel eloquent
提问by Anil P Babu
I have a different problem from this. The scenario is same but I am in need of more filtration of the results.
我有一个与此不同的问题。情况相同,但我需要对结果进行更多过滤。
Let me explain.
让我解释。
Consider I have 2 tables
考虑我有 2 张桌子
vehicles
车辆
id
name
staff_id
distance
mileage
staffs
职员
id
name
designation
I want to select only id
and name
from both tables(Models).
The Vehicle Model contain a belongsTo
relation to Staff model.
我只想选择id
和name
两个表(型号)。车辆模型包含belongsTo
与员工模型的关系。
class Vehicle extends Model
{
public function staff()
{
return $this->belongsTo('App\Staff','staff_id');
}
}
and I joined using this
我加入了使用这个
Vehicle::where('id',1)
->with(['staff'=> function($query){
// selecting fields from staff table
$query->select(['staff.id','staff.name']);
}])
->get();
When I put fields in ->get()
like this
当我->get()
像这样放入字段时
->get(['id','name'])
it filters the vehicle
table but produce no result of Staff table.
它过滤了vehicle
表,但没有产生 Staff 表的结果。
Any ideas?
有任何想法吗?
采纳答案by Anil P Babu
Finally found it..
In the ->get()
you have to put the 'staff_id' like this
终于找到了..在->get()
你必须把'staff_id'像这样
Vehicle::where('id',1)
->with(['staff'=> function($query){
// selecting fields from staff table
$query->select(['staff.id','staff.name']);
}])
->get(['id','name','staff_id']);
Since I didn't take the staff_id
, it couldn't perform the join and hence staff table fields were not shown.
由于我没有使用staff_id
,它无法执行连接,因此没有显示人员表字段。
回答by Sagar Gautam
You can use normal join like this:
您可以像这样使用普通连接:
Vehicle::join('staff','vehicles.staff_id','staff.id')
->select(
'vehicles.id',
'vehicles.name',
'staff.id as staff_id',
'staff.name'
)
->get();
Since, you can't take both id
at once in a join because only one is allowed. So, you can staff's id as staff_id
.
因为,你不能id
在一个连接中同时使用这两个,因为只允许一个。因此,您可以将员工的 id 设为staff_id
。
You can add vehicle id condition with where clause like:
您可以使用 where 子句添加车辆 ID 条件,例如:
Vehicle::join('staff','vehicles.staff_id','staff.id')
->where('vehicle.id',1)
->select(
'vehicles.id',
'vehicles.name',
'staff.id as staff_id',
'staff.name'
)
->get();
Hope you understand.
希望你能理解。