【问题标题】:laravel eloquent - can't eager load polymorphic relation with query 'select'laravel 雄辩 - 不能急切地使用查询“选择”加载多态关系
【发布时间】: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


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢!我不知道为什么这会起作用,因为我的两个语句之间生成的 SQL 是相同的,但是它起作用了!
    猜你喜欢
    • 2019-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多