- Goods working table goods
- Product language table GOOds_language
- Product resource table GOOds_image_map
Commodity list and language, resources belong to one-to-many relationship
- Business 1: Select *** from main table where name = ***
- Service 2: Query only the required data in the subtable
Commodity list model
Class GoodsModel extends the Model {/ / associated data public function language () {return $this - > hasMany (GoodsLanguageModel: : class, 'goods_id', 'id'); } public function goodsable(): \Hyperf\Database\Model\Relations\MorphTo {return $this-> MorphTo (); } / / associated resource data public function image () {return $this - > hasMany (GoodsImageMapModel: : class, 'goods_id', 'id')->orderByRaw('image_type asc,sort_id asc'); }}Copy the code
Commodity language table model
class GoodsLanguageModel extends Model
{
public function goods(): \Hyperf\Database\Model\Relations\MorphOne
{
return $this->morphOne(GoodsModel::class, 'goodsable',null,'id','goods_id');
}
}
Copy the code
Commodity resource list
class GoodsImageMapModel extends Model
{
}
Copy the code
The query implementation
use Hyperf\Database\Model\Builder; use Hyperf\Database\Model\Relations\Relation; Public function search(string $language,string $title,array $goodsIdList,int) {public function search(string $language,string $title,array $goodsIdList,int $status) { $model = GoodsModel::query(); / / the main table on state if ($status) {$model = $model - > where (' status' and '=', 1); $model = $model-> groupby (' groupby ',$goodsIdList); $languageRange = array_unique([$language,Context::get('mainLanguageCode')]); If ($title&&$title=urldecode($title)){ WhereHas ('language',function(Builder $query)use($title,$languageRange){$model = $model->whereHas('language',function(Builder $query)use($title,$languageRange){ $query->whereIn('language',$languageRange)->where('title','=',$title); }); } // The language data obtained is limited in scope, 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(); }}Copy the code