yii2 有个一对多的关联

新手提问 · lihongcheng · 于 5个月前 发布 · 359 次阅读

services里面的代码如下

public function jdgoodslist()
    {
        $params = [
            'mch_id' => 124,
            'goods_type' => 2,
            'purchase_type' => ForeignGoodsForm::GOODS_PURCHASE_TYPE['purchase'],
            'is_details' => (isset($this->is_details) && $this->is_details == 2) ? 2 :$this->is_details
        ];
        $params = array_filter($params);
        $goodlist = ForeignGoodsForm::getJdGoodList($params,Constants::PAGINATION,true);
        //获取商品分类数据
        $field = [
            'goods_cat_id',
            'goods_cat_name',
        ];
        $goodsCat = GoodsCatsForm::getGoodCatslist($field);
        $goodsCatList = array_column($goodsCat,'goods_cat_name','goods_cat_id');
        //处理数据
        foreach ($goodlist['list'] as &$goods) {
            $goods['goods_cat_name'] = isset($goodsCatList[$goods['goods_cat_id']]) && $goodsCatList[$goods['goods_cat_id']] ? $goodsCatList[$goods['goods_cat_id']] : '';
            $goods['goods_type_text'] = $goods['goods_type'] == 2 ? '京东' : '暂无';
            $goods['purchase_type_text'] = Constants::PURCHASE_TYPE_TEXT[$goods['purchase_type']];
            $goods['created'] = date('Y-m-d H:i:s', $goods['created']);
            unset($goods['goods_cat_id']);
        }
        return $goodlist['list'];
		}

模型代码如下

public static function getGoodsList($params, $is_pagination = Constants::PAGINATION, $returnTotal = false)
    {
        $offset = 0;
        if (!empty($params['page']) && !empty($params['page_size'])) {
            $offset = ($params['page'] - 1) * $params['page_size'];
        } else {
            $params['page_size'] = Constants::PAGE_SIZE;
        }
        $find = static::find()->alias('g')
            ->rightJoin(['gccr' => GoodsCompanyCatsRelationForm::tableName()], 'g.goods_id = gccr.goods_id')
            ->leftJoin(['gc' => GoodsCatsForm::tableName()],'gccr.goods_cat_id= gc.goods_cat_id')
            ->leftJoin(
                ['gw' => GoodsWareHouseForm::tableName()],
                'g.goods_warehouse_id= gw.goods_warehouse_id'
            )  // 商品信息表
            ->leftJoin(['gt' => GoodsAttrForm::tableName()],'g.goods_id = gt.goods_id')
        ->andWhere([
            'g.mch_id' => $params['mch_id'],
            'g.goods_type' => $params['goods_type'],
            'gccr.is_delete' => Constants::IS_DELETE,
            'g.is_delete' => Constants::IS_DELETE,
            'gw.is_delete'   => Constants::IS_DELETE,
        ]);
        //匹配商品名称搜索
        if (isset($params['goods_name']) && !empty(trim($params['goods_name']))) {
            $find->andWhere(['like', 'gw.goods_name', $params['goods_name']]);
        }

        $addfield = [
            'g.attr_groups',
            'gw.pic_url',
            'gw.detail',
        ];
        $field = [
            'g.goods_id',
            'g.goods_warehouse_id',
            'g.mch_id',
            'g.status',
            'g.goods_type',
            'gc.goods_cat_id',
            'gw.cover_pic',
            'gw.goods_name',
            'g.purchase_type',
            'g.created'
        ];
        $find->distinct()->select($field);
        if ($params['is_details'] == 2) {
            $find->addSelect($addfield);
            $find->with([
                'attr' => function($query) {
                    $query->orderBy(['at.platform_price' => 3])->select([
                        'at.goods_attr_id',
                        'at.sign_id',
                        'at.pic_url',
                        'at.platform_price',
                    ]);
                }
            ]);
        }
        $query = self::buildParams($find, $params);
        //是否分页显示
        $is_pagination && $query->offset($offset)->limit($params['page_size']);
        $total = 0;
        if ($returnTotal) {
            $total = $query->count();
        }
        $query = $query->groupBy('g.goods_id');
        if ($returnTotal) {
            return [
                'total' => $total,
                'list' => $query->asArray()->all(),
            ];
        }
    }
public static function buildParams($find, $params, $fields = [])
    {
        if ($fields) {
            $find->select($fields);
        }
        //商品ID
        if (isset($params['goods_id']) && !empty($params['goods_id'])) {
            $find->andWhere(['g.goods_id' => $params['goods_id']]);
        }

        //分类ID
        if (isset($params['goods_cat_id']) && !empty($params['goods_cat_id'])) {
            $find->andWhere(['gccr.goods_cat_id' => $params['goods_cat_id']]);
        }

        //商品购买类型
        if (isset($params['purchase_type']) && !empty($params['purchase_type'])) {
            $find->andWhere(['g.purchase_type' => $params['purchase_type']]);
        }

        if (isset($params['not_goods_id']) && !empty($params['not_goods_id'])) {
            $find->andWhere(['not in', 'g.goods_id', $params['not_goods_id']]);
        }

        //是否返回商品指定产品线及企业相关信息,否则会重复
        if (isset($params['type']) && $params['type'] == 1) {
            $find->leftJoin(['pg' => ProductGoodsForm::tableName()], 'g.goods_id = pg.goods_id')
                ->andWhere(['pg.is_delete' => Constants::IS_DELETE]);
            $find->addSelect([
                'pg.initial_purchase_quantity as pg_initial_purchase_quantity',
                'pg.price as pg_price',
                'pg.shelf_status as pg_status',
                'pg.scribing_price as pg_scribing_price',
            ]);
        }
        $find->andWhere(["g.is_delete" => Constants::IS_DELETE]);

        return $find;
    }
public function getAttr()
    {
        return $this->hasMany(
            GoodsAttrForm::class,
            ['goods_id' => 'goods_id'])
            ->where(['at.is_delete' => Constants::IS_DELETE])
            ->alias('at');
    }


返回结果如下
{
		"goods_id": "191146995036336128",
		"goods_warehouse_id": "191146995032141824",
		"mch_id": "236243043703373824",
		"status": "1",
		"goods_type": "6",
		"goods_cat_id": "179691298767646720",
		"cover_pic": "https://zxyp-quanzong-1.oss-cn-beijing.aliyuncs.com/uploads/mall/23627212696956108820220902160529/5b537cfb0ee26e86c655d7460230f6b2.jpg",
		"goods_name": "鹏程五花块500g",
		"purchase_type": "2",
		"created": "1659636615",
		"attr_groups": "[{\"attr_group_id\":1,\"attr_group_name\":\"规格\",\"attr_list\":[{\"attr_id\":2,\"attr_name\":\"默认\"}]}]",
		"pic_url": "[\"https://zxyp-quanzong-1.oss-cn-beijing.aliyuncs.com/uploads/mall/23627212696956108820220902160529/5b537cfb0ee26e86c655d7460230f6b2.jpg\",\"https://zxyp-quanzong-1.oss-cn-beijing.aliyuncs.com/uploads/mall/23627212696956108820220902160526/bd2bb562068fd09aadd383f28943b2f2.jpg\",\"https://zxyp-quanzong-1.oss-cn-beijing.aliyuncs.com/uploads/mall/23627212696956108820220902160523/3c33165ac4b8f1aa37b9273c3280773c.jpg\"]",
		"detail": "<p>鹏程五花块500g</p><p><br></p><p><img src=\"https://zxyp-quanzong-1.oss-cn-beijing.aliyuncs.com/uploads/mall/23627212696956108820220902160529/5b537cfb0ee26e86c655d7460230f6b2.jpg\"><img src=\"https://zxyp-quanzong-1.oss-cn-beijing.aliyuncs.com/uploads/mall/23627212696956108820220902160526/bd2bb562068fd09aadd383f28943b2f2.jpg\"><img src=\"https://zxyp-quanzong-1.oss-cn-beijing.aliyuncs.com/uploads/mall/23627212696956108820220902160523/3c33165ac4b8f1aa37b9273c3280773c.jpg\"></p>",
		"attr": []
	}
问一下这个attr数据为啥是空呢
共收到 1 条回复
forecho#13个月前 0 个赞

在你的代码中,attr数据字段是通过关联查询获取的,如果attr字段返回的数据为空,可能有以下几个原因:

  1. 数据库中没有对应的GoodsAttrForm记录:你可以通过数据库查询,看看在GoodsAttrForm表中,是否存在与goods_id相关的记录。

  2. 关联查询条件不满足:你使用的是hasMany关联查询,所以需要确认GoodsAttrForm模型中的goods_id是否存在并且与主查询模型的goods_id匹配。

  3. 查询条件限制:在关联查询中,你添加了查询条件->where(['at.is_delete' => Constants::IS_DELETE]),这可能会限制查询结果。请确认数据库中的is_delete字段是否满足这个条件。

你可以尝试在getAttr()函数中先移除查询条件,然后看是否能获取到数据。如果还是获取不到数据,可以尝试直接在数据库中执行SQL查询,检查是否存在相应的记录。

另外,你的attr查询是在$params['is_details'] == 2时才添加到主查询中的,因此你需要确认is_details参数是否为2。

以上就是可能的原因和解决方式,希望可以帮助你。

添加回复 (需要登录)
需要 登录 后方可回复, 如果你还没有账号请点击这里 注册