laravel跨库多态关联实战

点赞记录表做了分库分表,位于副库里面

image.png

表结构

image.png

该点赞表关联了8个不同的表,因为业务原因,评论回复表有四个板块,所以做了4个评论记录表,4个回复记录表,且结构有细微不同。

目标是用户获得被点赞记录,根据不同的type值关联到不同的评论或者回复。

上代码。。。。。

<?php

namespace App\Model\Member;

use App\Model\BaseModel;
use App\Model\Circle\CircleCommentModel;
use App\Model\Circle\CircleCommentSubModel;
use App\Model\Group\GroupCommentModel;
use App\Model\Group\GroupCommentSubModel;
use App\Model\Interview\InterviewCommentModel;
use App\Model\Interview\InterviewCommentSubModel;
use App\Model\Library\LibraryCommentModel;
use App\Model\Library\LibraryCommentSubModel;

class MemberLikeModel extends BaseModel
{
    public $connection = "mysql_logs";
    public $timestamps = false;
    public $table = "member_like";


    public function getCommentTypeAttribute($val)
    {
        $map = [
            1 => LibraryCommentModel::class,
            2 => LibraryCommentSubModel::class,
            3 => InterviewCommentModel::class,
            4 => InterviewCommentSubModel::class,
            5 => CircleCommentModel::class,
            6 => CircleCommentSubModel::class,
            7 => GroupCommentModel::class,
            8 => GroupCommentSubModel::class
        ];

        $data = $map[$this->type] ?? LibraryCommentModel::class;
        return $this->attributes['comment_type'] = $data;
    }

    public function content()
    {
        return $this->morphTo('content', 'comment_type', 'pid');
    }

    public function member()
    {
        return $this->hasOne(MemberModel::class, 'id', 'member_id');
    }
}

public $connection = "mysql_logs";指定了该member_like表到副库,并且从baseModel继承了两个分表取模方法。

// 设置表后缀
public function setSuffix(int $suffix, int $mold)
{
    if ($suffix > 0) {
        $suffix      = intval($suffix % $mold) + 1;
        $this->table = $this->getTable() . '_' . $suffix;
    }
}

// 提供一个静态方法设置表后缀
public static function suffix(int $suffix = 0, int $mold = 20)
{
    $instance = new static;
    $instance->setSuffix($suffix, $mold);

    return $instance->newQuery();
}

还设置了一个获取器,

getCommentTypeAttribute

因为之前的逻辑只存放了type为int值。但是多态关联需要使用到模型名称,所以通过一个获取器给模型追加一个comment_type字段并计算到相应的模型名。

被关联到评论表以其中一个举例

public $connection = 'mysql';

public function content()
{
    return $this->morphOne(MemberLikeModel::class, 'content', 'comment_type', 'pid', 'id');
}

最终实现了跨表跨库多态关联

上使用方法

public function history_like(int $member_id, int $count)
{
    $data = MemberLikeModel::suffix($member_id, 20)->with(['content',self::$With_Member])
        ->where('return_id', $member_id)
        ->orderByDesc('id')
        ->paginate($count);
    return $data;
}

 

转载于申研社-陈杰 http://blog.95shouyou.com/?id=11

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值