繁体   English   中英

laravel 5.4多态关系-渴望通过查询范围读取

[英]laravel 5.4 polymorphic relation - eager read via query scope

我有一个多态关系,其中表'map_nodes'与'system_constants'一对多。

我似乎无法使用查询范围来渴望加载system_constants。 没有错误,没有记录。

这是我的模特。 我只包括一个模型“ 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');
  }      
}

这是我在system_constants表中拥有的:

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

请注意,我确实定义了Relation :: morphMap,这使我可以在imageable_type中使用“节点”。

这是我正在运行的:

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

我已打开sql日志记录,并且看到上述两个查询的正确SQL。 我可以在SQL工具(带参数替换)中使用该确切查询,并且可以正常工作-它返回记录:

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

任何帮助表示赞赏。

我不确定,但这似乎奏效了。 我只是删除了查询范围,并做了一个明确的“ with”。

$ temp = MapNodes :: with('SystemConstants')-> find(25786);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM