building-sign/app/traits/account/AccountRecordTrait.php

124 lines
3.5 KiB
PHP
Executable File

<?php
namespace app\traits\account;
use Exception;
use think\Collection;
use app\model\AccountRecord;
use think\db\exception\DbException;
use app\exception\RepositoryException;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
trait AccountRecordTrait
{
/**
* 收藏|关注
*
* @param int $accountId
* @param int $goodsId
* @param string $type
* @return bool
* @throws DataNotFoundException
* @throws DbException
* @throws ModelNotFoundException
*/
public function collectGoods(int $accountId, int $goodsId, string $type): bool
{
return AccountRecord::collect($accountId, $goodsId, $type);
}
/**
* 取消收藏|关注
*
* @param int $accountId
* @param int $goodsId
* @return bool
* @throws DataNotFoundException
* @throws DbException
* @throws ModelNotFoundException
*/
public function unCollectGoods(int $accountId, int $goodsId): bool
{
return AccountRecord::unCollect($accountId, $goodsId);
}
/**
* 获取指定账户收藏列表
*
* @param int $accountId
* @param string $type goods|auction|special
* @return array
* @throws RepositoryException|Exception
*/
public function getCollectedIds(int $accountId, string $type = ''): array
{
if ($type) {
$where[] = ['type', '=', $type];
}
$where[] = ['account_id', '=', $accountId];
$where[] = ['action', '=', AccountRecord::ACTION_COLLECT];
$where[] = ['is_collected', '=', 1];
return AccountRecord::findList($where)['list']->column('goods_id');
}
/**
* 是否收藏
*
* @param int $accountId
* @param int $goodsId
* @param string $type goods|auction|special
* @return bool
*/
public function isCollected(int $accountId, int $goodsId, string $type): bool
{
return AccountRecord::where('account_id', $accountId)
->where('goods_id', $goodsId)
->where('type', $type)
->where('action', AccountRecord::ACTION_COLLECT)
->where('is_collected', AccountRecord::COLLECTED)
->count() > 0;
}
/**
* 获取用户收藏记录
*
* @param int $accountId
* @param string $type
* @param int $page
* @param int $size
* @return Collection
* @throws DataNotFoundException
* @throws DbException
* @throws ModelNotFoundException
*/
public function fetchCollection(int $accountId, string $type = '', int $page = 1, int $size = 20): Collection
{
return AccountRecord::with(['goods'])
->when(!empty($type), function ($q) use ($type) {
$q->where('type', $type);
})
->where('account_id', $accountId)
->where('is_collected', AccountRecord::COLLECTED)
->where('type', $type)
->page($page, $size)
->select();
}
/**
* 批量查询是否收藏
* 返回收藏的ID列表
*
* @param int $accountId 用户ID
* @param array $ids 记录ID
* @return array
*/
public function findCollectionByIds(int $accountId, array $ids): array
{
return AccountRecord::where('account_id', $accountId)
->where('id', 'in', $ids)
->where('is_collected', AccountRecord::COLLECTED)
->where('type', AccountRecord::ACTION_COLLECT)
->column('id');
}
}