如何从连接表中选择列:laravel eloquent

时间:2017-08-01 12:19:12

标签: php laravel eloquent laravel-eloquent

this我遇到了另一个问题。情景相同,但我需要对结果进行更多过滤。

让我解释一下。

考虑我有2张桌子

车辆

 id
 name
 staff_id
 distance
 mileage

人员

 id
 name
 designation

我想从两个表(模型)中仅选择idname。 车辆模型包含与员工模型的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表的结果。

有什么想法吗?

4 个答案:

答案 0 :(得分:3)

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

答案 1 :(得分:2)

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

Vehicle::join('staff','vehicles.staff_id','staff.id')
         ->select(
                  'vehicles.id',
                  'vehicles.name',
                  'staff.id as staff_id',
                  'staff.name'
          )
         ->get();

因为,您无法在联接中同时使用id,因为只允许一个。{1}}。因此,您可以将员工的身份标识为staff_id

您可以使用where子句添加vehicle 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();

希望你明白。

答案 2 :(得分:1)

试试这个:

Vehicle::where('id',1)
    ->with(['staff'=> function($query){
        // selecting fields from staff table
        $query->select('id','name');
    }])
    ->get();

答案 3 :(得分:0)

我猜最简单快捷的方式是:

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

应该显示外键供选择。

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

with('staff:id,name' )

用于粒度选择。

相关问题