ThinkPHP 模型关联问题

浏览:720 发布日期:2020/10/22 分类:ThinkPHP6专区 关键字: 模型关联
问题1:在Model中添加两个hasOne关联同一个表,使用关联查询时,只能查询一个class InvitationCode extends Model
{
    public static function tablePk(): string
    {
        return 'id';
    }

    public static function tableName(): string
    {
        return 'invitation_code';
    }

    public function oneReciver()
    {
        return $this->hasOne(User::class, 'uid', 'reciver_id')->bind([
            'reciver' => 'real_name'
        ]);
    }

    public function oneSender()
    {
        return $this->hasOne(User::class, 'uid', 'sender_id')->bind([
            'sender' => 'real_name',
        ]);
    }
}

// 调用代码,输出的结果是只能返回第二个with中的数据
        $invitationCodeModel = InvitationCode::getDB();
        try {
            // ★ 字符串查询
            $invitationCode = $invitationCodeModel
                ->with('oneReciver')
                ->with('oneSender')
                ->select();

            echo var_export($invitationCode->toArray(), true);
        } catch (\Throwable $th) {
            echo $th->getMessage();
        } finally {
            echo $invitationCodeModel->getLastSql();
        }
问题2:如果想用withJson时,出现异常        $invitationCodeModel = InvitationCode::getDB();
        try {
            // ★ 字符串查询
            $invitationCode = $invitationCodeModel
                ->withJoin('oneReciver', 'INNER')
                ->withJoin('oneSender', 'INNER')
                ->select();

            echo var_export($invitationCode->toArray(), true);
        } catch (\Throwable $th) {
            echo $th->getMessage();
        } finally {
            echo $invitationCodeModel->getLastSql();
        }
最佳答案
评论( 相关
后面还有条评论,点击查看>>