jeudi 24 août 2017

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

I'm running Laravel 5.4 and for some reason I cannot do a column select on a 1-to-many polymorphic relation. I want to limit the columns returned in the related table.

Here's my '1 side' of my 1-to-many relationship:

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');
    }
}

Here's my 'many side' table in the relationship:

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

Here's two ways I'm trying to call it. One gets all the columns on SystemConstants, and the second I just want two columns:

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

Why does the first call return the related records, but not the second? The below SQL statements for both calls look exactly the same (with the exception that I'm only wanting two columns in the second call).

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";}



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2xhi925
via IFTTT

Aucun commentaire:

Enregistrer un commentaire