thinkphp5 MorphToOne【bug】多态一对一 使用关联预载入模式不能查询到关联数据

tp5.0.24 MorphToOne.php 中原来方法为

/**
     * 多态一对多 关联模型预查询
     * @access   public
     * @param array         $where       关联预查询条件
     * @param string        $relation    关联名
     * @param string        $subRelation 子关联
     * @param bool|\Closure $closure     闭包
     * @return array
     */
    protected function eagerlyMorphToOne($where, $relation, $subRelation = '', $closure = false)
    {
        // 预载入关联查询 支持嵌套预载入
        if ($closure) {
            call_user_func_array($closure, [ & $this]);
        }
        $list     = $this->query->where($where)->with($subRelation)->find();
        $morphKey = $this->morphKey;
        // 组装模型数据
        $data = [];
        foreach ($list as $set) {
            $data[$set->$morphKey][] = $set;
        }
        return $data;
    }

修改为

 /**
     * 多态一对一 关联模型预查询
     * @access   public
     * @param array         $where       关联预查询条件
     * @param string        $relation    关联名
     * @param string        $subRelation 子关联
     * @param bool|\Closure $closure     闭包
     * @return array
     */
    protected function eagerlyMorphToOne($where, $relation, $subRelation = '', $closure = false)
    {
        // 预载入关联查询 支持嵌套预载入
        if ($closure) {
            call_user_func_array($closure, [ & $this]);
        }
        $list     = $this->query->where($where)->with($subRelation)->select();
        $morphKey = $this->morphKey;
        // 组装模型数据
        $data = [];
        foreach ($list as $set) {
            $data[$set->$morphKey] = $set;
        }
        return $data;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
ThinkPHP6中,实现一对多关联查询的方法是使用hasMany模式。具体设置方式如下: 1. 在主表的模型中使用hasMany方法进行关联设置: ``` public function 附表名() { return $this->hasMany(附表模型::class, '外键字段', '主键字段'); } ``` 例如: ``` public function profile() { return $this->hasMany(Profile::class, 'user_id', 'id'); } ``` 2. 进行一对多关联查询: ``` $user = UserModel::find(主表记录的id); return json($user->附表关联方法名); ``` 例如: ``` $user = UserModel::find(19); return json($user->profile); ``` 3. 进行数据筛选查询: ``` $user->附表关联方法名->where('条件字段', '条件操作符', '条件值'); ``` 例如: ``` $user->profile->where('id', '>=', 10); ``` 4. 使用has()方法查询满足条件的主表记录: ``` UserModel::has('附表关联方法名', '条件操作符', '条件值')->select(); ``` 例如: ``` UserModel::has('profile', '>=', 2)->select(); ``` 5. 使用together()方法,在删除主表记录时,同时删除关联的附表记录: ``` $user = UserModel::with('附表关联方法名')->find(主表记录的id); $user->together(['附表关联方法名'])->delete(); ``` 例如: ``` $user = UserModel::with('profile')->find(22); $user->together(['profile'])->delete(); ``` 以上就是在ThinkPHP6中实现一对多关联查询的方法。希望对你有所帮助。<span class="em">1</span><span class="em">2</span><span class="em">3</span><span class="em">4</span>

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值