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
				
        
 
            
        - 如何使用 Google API 在团队云端硬盘中创建文件夹? 2022-01-01
 - openssl_digest vs hash vs hash_hmac?盐与盐的区别HMAC? 2022-01-01
 - 覆盖 Magento 社区模块控制器的问题 2022-01-01
 - 使用 GD 和 libjpeg 支持编译 PHP 2022-01-01
 - 如何从数据库中获取数据以在 laravel 中查看页面? 2022-01-01
 - Laravel 5:Model.php 中的 MassAssignmentException 2021-01-01
 - Oracle 即时客户端 DYLD_LIBRARY_PATH 错误 2022-01-01
 - PHP - if 语句中的倒序 2021-01-01
 - 如何在 Symfony2 中正确使用 webSockets 2021-01-01
 - PHP foreach() 与数组中的数组? 2022-01-01
 
