我有一个与 这个不同的问题.场景相同,但我需要对结果进行更多过滤.
I have a different problem from this. The scenario is same but I am in need of more filtration of the results.
让我解释一下.
考虑我有 2 张桌子
车辆
id
name
staff_id
distance
mileage
员工
id
name
designation
我只想从两个表(模型)中选择 id
和 name
.Vehicle Model 包含与 Staff 模型的 belongsTo
关系.
I want to select only id
and name
from both tables(Models).
The Vehicle Model contain a belongsTo
relation to Staff model.
class Vehicle extends Model
{
public function staff()
{
return $this->belongsTo('AppStaff','staff_id');
}
}
我加入使用这个
Vehicle::where('id',1)
->with(['staff'=> function($query){
// selecting fields from staff table
$query->select(['staff.id','staff.name']);
}])
->get();
当我像这样将字段放在 ->get()
中时
When I put fields in ->get()
like this
->get(['id','name'])
它过滤了vehicle
表,但没有产生Staff表的结果.
it filters the vehicle
table but produce no result of Staff table.
有什么想法吗?
终于找到了..在 ->get()
中,你必须像这样输入 'staff_id'
Finally found it..
In the ->get()
you have to put the 'staff_id' like this
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
,它无法执行连接,因此没有显示人员表字段.
Since I didn't take the staff_id
, it couldn't perform the join and hence staff table fields were not shown.
这篇关于如何从连接表中选择列:laravel eloquent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!