How to select columns from joined tables: laravel eloquent(如何从连接表中选择列:laravel eloquent)
问题描述
我有一个与 这个不同的问题.场景相同,但我需要对结果进行更多过滤.
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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何从连接表中选择列:laravel eloquent
基础教程推荐
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 如何替换eregi() 2022-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
- 如何在 Laravel 中使用 React Router? 2022-01-01
