【发布时间】:2018-02-03 01:31:52
【问题描述】:
我正在运行 Laravel 5.4,由于某种原因,我无法对一对多的多态关系进行列选择。我想限制相关表中返回的列。
这是我的一对多关系的“一方面”:
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');
}
}
这是我在关系中的“多方”表:
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);
为什么第一次调用返回相关记录,而第二次没有?下面两个调用的 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";}
【问题讨论】:
标签: php laravel-5 eloquent polymorphic-associations