Skip to content

Instantly share code, notes, and snippets.

@eddy8
Created November 22, 2021 02:02
Show Gist options
  • Save eddy8/e6aae7b5fc73207109e4f1ec43448a22 to your computer and use it in GitHub Desktop.
Save eddy8/e6aae7b5fc73207109e4f1ec43448a22 to your computer and use it in GitHub Desktop.
laravel Eloquent seperate table
<?php
namespace App\Model;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
/**
* 分表关联数据加载
*/
trait MultiTable
{
public static function getRelationData(Collection $data, $related, $foreignKey, $fields = '*', $ownerKey = 'id')
{
// 找出要操作的表
$tables = [];
$data->each(function ($item) use (&$tables) {
array_push($tables, $this->getTableName($item->{$ownerKey}));
});
$tables = array_unique($tables);
// 构建 union 查询
$queries = collect();
$ids = $data->pluck($ownerKey)->join(',');
foreach ($tables as $table) {
$queries->push("select {$fields} from {$table} where {$foreignKey} in ({$ids})");
}
return (new $related)
->setTable(DB::raw('(' . $queries->join(' union all ') . ') as temp_table'))
->get();
}
public static function loadRelationData(Collection $data, $relationName, $related, $foreignKey, $type = 'all', $fields = '*', $ownerKey = 'id')
{
$relationData = static::getRelationData($data, $related, $foreignKey, $fields, $ownerKey);
$data->transform(function ($item) use ($relationData, $foreignKey, $type, $relationName) {
$item->setRelation($relationName, $relationData->where($foreignKey, $item->{$ownerKey})->{$type}());
return $item;
});
return $data;
}
public abstract function getTableName($id);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment