[英]Laravel Eloquent: How to get only certain columns from joined tables
[英]How to select columns from joined tables: laravel eloquent
我有一个与此不同的问题。 情况相同,但我需要对结果进行更多过滤。
让我解释一下。
考虑我有 2 张桌子
车辆
id
name
staff_id
distance
mileage
职员
id
name
designation
我只想从两个表(模型)中选择id
和name
。 Vehicle Model 包含一个与 Staff 模型的belongsTo
关系。
class Vehicle extends Model
{
public function staff()
{
return $this->belongsTo('App\Staff','staff_id');
}
}
我加入了使用这个
Vehicle::where('id',1)
->with(['staff'=> function($query){
// selecting fields from staff table
$query->select(['staff.id','staff.name']);
}])
->get();
当我像这样将字段放入->get()
->get(['id','name'])
它过滤了vehicle
表,但没有产生员工表的结果。
有什么想法吗?
终于找到了..在->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']);
由于我没有使用staff_id
,它无法执行连接,因此没有显示员工表字段。
您可以像这样使用普通连接:
Vehicle::join('staff','vehicles.staff_id','staff.id')
->select(
'vehicles.id',
'vehicles.name',
'staff.id as staff_id',
'staff.name'
)
->get();
因为,您不能在连接中同时使用两个id
,因为只允许使用一个。 因此,您可以将员工的 id 设为staff_id
。
您可以使用 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();
希望你明白。
试试这个:
Vehicle::where('id',1)
->with(['staff'=> function($query){
// selecting fields from staff table
$query->select('id','name');
}])
->get();
我猜最短和更方便的方法是:
Vehicle::select('id','name','staff_id')->where('id',1)
->with('staff:id,name' )->get();
外键应存在以供选择。
从 Laravel 5.7 开始,你可以像这样使用 with() :
with('staff:id,name' )
用于粒度选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.