laravel跨库多态关联实战
点赞记录表做了分库分表,位于副库里面
表结构
该点赞表关联了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;
}
