代码结构优化: 请问怎么判断数据不再当前表中就去另一个表中查询

现在的代码结构感觉过于耦合, 请问怎么优化下.


    if (Cache::has('api_get_city_name_' . $id)) {
        return Cache::get('api_get_city_name_' . $id);
    }

    $rows = \App\Models\CommodityTicket::select('province', 'city')->find($id);
    $rows = empty($rows) ? \App\Models\ScenicSpot::select('province', 'city')->find($id) : $rows;
    $rows = empty($rows) ? \App\Models\Advertorial::select('province', 'city')->find($id) : $rows;

    if (empty($rows)) return Cache::remember('api_get_city_name_' . $id, 600, function () {
        return '';
    });
    .
    .
    .
《L01 基础入门》
我们将带你从零开发一个项目并部署到线上,本课程教授 Web 开发中专业、实用的技能,如 Git 工作流、Laravel Mix 前端工作流等。
《L03 构架 API 服务器》
你将学到如 RESTFul 设计风格、PostMan 的使用、OAuth 流程,JWT 概念及使用 和 API 开发相关的进阶知识。
讨论数量: 1
qiuyuhome
use App\Models\CommodityTicket;
use App\Models\ScenicSpot;
use App\Models\Advertorial;

public function demo(int $id) 
{
    $cacheName = 'api_get_city_name_' . $id;
    $cacheTime = 600;
    return Cache::remember($cacheName, $cacheTime, function () use ($id) {
        /**
         * 基于现在的表结构, 肯定是需要每个表都查一遍的.
         * 可以考虑新建一张表, 字段为: id, table_name(对应的哪个表), refer_id(查询这个 3 个表使用的 id).
         * 下面是基于你的现有的逻辑, 我的优化. 没想到更高的办法.
         */

        $rows = CommodityTicket::find($id, ['province', 'city']);
        if ($rows) {
            return $rows;
        }

        $rows = ScenicSpot::find($id, ['province', 'city']);
        if ($rows) {
            return $rows;
        }

        return Advertorial::find($id, ['province', 'city']);
    });
}
4年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!