【问题标题】:How to select columns from joined tables: laravel eloquent如何从连接表中选择列:laravel eloquent
【发布时间】:2018-01-08 07:23:24
【问题描述】:

我遇到了与this 不同的问题。场景相同,但我需要对结果进行更多过滤。

让我解释一下。

假设我有 2 张桌子

车辆

 id
 name
 staff_id
 distance
 mileage

员工

 id
 name
 designation

我只想从两个表(模型)中选择 idname。 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 表,但不产生 Staff 表的结果。

有什么想法吗?

【问题讨论】:

    标签: php laravel eloquent laravel-eloquent


    【解决方案1】:

    我猜最短和更方便的方法是:

    Vehicle::select('id','name','staff_id')->where('id',1)
    ->with('staff:id,name' )->get();
    

    应提供外键以供选择。

    从 Laravel 5.7 开始,您可以像这样使用 with() :

    with('staff:id,name' )
    

    用于精细选择。

    【讨论】:

      【解决方案2】:

      终于找到了。。 在->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,它无法执行连接,因此未显示人员表字段。

      【讨论】:

        【解决方案3】:

        您可以像这样使用普通连接:

        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();
        

        希望你能理解。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2019-06-15
          • 2013-01-21
          • 2015-05-08
          • 2017-08-22
          • 2021-12-24
          • 2021-12-21
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多