hyperf關聯子表查詢主表資料

芭菲雨發表於2021-12-10

  1. 商品表goods
  2. 商品語言表goods_language
  3. 商品資源表goods_image_map

商品表與【語言、資源】屬於一對多的關係

  • 業務1:查詢語言表裡面標題等於*** 的商品主表資料
  • 業務2:查詢出的子表資料,僅僅查詢需要的資料

商品表模型

class GoodsModel extends Model
{

    //關聯語言資料
    public function language()
    {
        return $this->hasMany(GoodsLanguageModel::class, 'goods_id', 'id');
    }
    //查詢使用的配置
    public function goodsable(): \Hyperf\Database\Model\Relations\MorphTo
    {
        return $this->morphTo();
    }
    //關聯資源資料
    public function image()
    {
        return $this->hasMany(GoodsImageMapModel::class, 'goods_id', 'id')->orderByRaw('image_type asc,sort_id asc');
    }

}

商品語言表模型

class GoodsLanguageModel extends Model
{
    public function goods(): \Hyperf\Database\Model\Relations\MorphOne
    {
        return $this->morphOne(GoodsModel::class, 'goodsable',null,'id','goods_id');
    }
}

商品資源表

class GoodsImageMapModel extends Model
{

}

查詢實現

use Hyperf\Database\Model\Builder;
use Hyperf\Database\Model\Relations\Relation;

class Test
{
    //根據商品ID和語言子表的標題進行查詢商品資料
    public function search(string $language,string $title,array $goodsIdList,int $status)
    {
        $model = GoodsModel::query();
        //主表上架狀態
        if($status){
            $model = $model->where('status','=',1);
        }
        //主表ID範圍
        if($goodsIdList){
            $model = $model->whereIn('id',$goodsIdList);
        }
        //篩選子表的語言標識的欄位範圍
        $languageRange = array_unique([$language,Context::get('mainLanguageCode')]);

        if($title&&$title=urldecode($title)){
            //查詢子表裡麵包含$title的主表資料,並且在語言範圍的
            $model = $model->whereHas('language',function(Builder $query)use($title,$languageRange){
                $query->whereIn('language',$languageRange)->where('title','=',$title);
            });
        }
        //獲取到的語言資料有範圍限制,資源資料有篩選條件和排序
        return $model->with([
            "language" => function(Relation $relation)use($languageRange){
                return $relation->getQuery()->whereIn('language',$languageRange)->select(['id','goods_id','language','title','description']);
            },
            'image'=>function(Relation $relation){
                return $relation->getQuery()->where('resources_type','=',1)->orderByRaw('image_type asc,sort_id asc')->select(['id','goods_id','resources_id','sort_id','image_type']);
            }])->select(['id','status','shop_id'])->get()->toArray();

    }
}

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章