laravel eloquent - 无法通过查询 'select' 急切加载多态关系

laravel eloquent - can't eager load polymorphic relation with query 'select'

我是 运行 Laravel 5.4,出于某种原因,我无法在一对多多态关系上创建列 select。我想在相关 table.

中限制列 returned

这是一对多关系的“一侧”:

class MapNodes extends Model {

    protected $table = 'map_nodes';
    protected $fillable = ['title'];
    protected $validations = ['title' => 'max:200|string' ];
    public function SystemConstants() {
        return $this->morphMany('App\Modules\Models\SystemConstants', 'imageable');
    }
}

这是我的 'many side' table 关系:

class SystemConstants extend Model {

    protected $table = 'system_constants';
    protected $fillable = ['name','imageable_id','imageable_type'];
    protected $validations = ['name' => 'max:200|string',
                              'imageable_id' => 'integer|required',
                              'imageable_type' => 'max:45|string'];

    // define this model as polymorphic
    public function imageable() {
        return $this->morphTo();
    }        
}

这是我尝试调用它的两种方式。一个获取 SystemConstants 上的所有列,第二个我只想要两列:

  $temp = MapNodes::with('SystemConstants')->find(25786);
  $temp = MapNodes::with([ 'SystemConstants' =>
    function( $query ) {
      return $query->select('system_constants.id', 'system_constants.name' );
    } ])->find(25786);

为什么第一个调用return相关记录,而第二个不调用?以下两个调用的 SQL 语句看起来完全相同(除了我在第二次调用中只想要两列)。

select * from `system_constants` where 
    `system_constants`.`imageable_id` in (?) and 
    `system_constants`.`imageable_type` = ? - a:2:{i:0;i:25786;i:1;s:5:"Nodes";}

select `system_constants`.`id`, `system_constants`.`name` from   `system_constants` where 
    `system_constants`.`imageable_id` in (?) and 
    `system_constants`.`imageable_type` = ? - a:2:{i:0;i:25786;i:1;s:5:"Nodes";}

为了工作,您必须在 select 语句中同时添加外键和主键:

$temp = MapNodes::with([ 'SystemConstants' =>
    function( $query ) {
      return $query->select('system_constants.id', 'system_constants.name', 'system_constants.imageable_id');
    } ])->find(25786);