lundi 3 juillet 2017

laravel 5.4 polymorphic relation - eager read via query scope

I have a polymorphic relation where a table 'map_nodes' has a one-to-many to 'system_constants'.

I can't seem to use a query scope to eager load system_constants. No errors, just no records.

Here's my models. I've only included one model 'map_nodes':

namespace App\Modules\Olab\Models;

class SystemConstants extends BaseModel {
  // Database:
  //   id INT(11) PK
  //   imageable_id INT(11)
  //   imageable_type VARCHAR(45)
  //   value BLOB
  public function imageable() {
      return $this->morphTo();
  }
}

class MapNodes extends BaseModel {

  public function scopeConstants( $query )  {
    $query->with( [ 'SystemConstants' => function ( $query ) {
        $query->select( 'system_constants.id',
                        'system_constants.value' );
    } ] );
  }

  public function SystemConstants() {
    return $this->morphMany('App\Modules\Olab\Models\SystemConstants', 'imageable');
  }      
}

This is what I have in system_constants table:

id, imageable_id, imageable_type, value
'1904', '25786', 'Nodes', <blob>

Note that I do have a Relation::morphMap defined, which allows me to use 'Nodes' in imageable_type.

This is what I'm running:

// returns collection of system_constant records
$temp = MapNodes::find(25786)->SystemConstants;  
// doesn't work.  get map_nodes record, but no eager load of system_constants
$temp = MapNodes::find(25786)->Constants()->first();

I have sql logging turned on and I see the correct SQL for both above queries. I can take that exact query in an SQL tool (with param substitution) and it works - it returns records:

select `system_constants`.`id`, `system_constants`.`value` 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";}

Any help appreciated.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire