實(shí)現(xiàn)方法添加類(lèi): App\Restructure\Relations\HasManyFromStr
用于處理關(guān)聯(lián)方法
此類(lèi)是參考 Illuminate\Database\Eloquent\Relations\HasMany 做的對(duì)應(yīng)改動(dòng)
代碼如下
namespace App\Restructure\Relations;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Collection;
class HasManyFromStr extends HasMany
{
protected $separator = ','; //分隔符
protected $strict;
public function __construct(Builder $query, Model $parent, string $foreignKey, string $localKey, $separator, $strict = false)
{
$this->separator = $separator;
$this->strict = $strict; //元素執(zhí)行函數(shù) true 代表轉(zhuǎn)為int
parent::__construct($query, $parent, $foreignKey, $localKey);
}
/**
* 重寫(xiě)獲取單個(gè)模型建方法
*/
public function addConstraints()
{
if (static::$constraints) {
$this->query->whereIn($this->foreignKey, $this->handleIn($this->separator, $this->getParentKey()));
$this->query->whereNotNull($this->foreignKey);
}
}
/**
* 重寫(xiě)獲取所有主鍵方法.
*
* @param array $models
* @param string $key
* @return array
*/
protected function getKeys(array $models, $key = null)
{
$keysArr = [];
collect($models)->map(function ($value) use ($key, &$keysArr) {
$result = $key ? $value->getAttribute($key) : $value->getKey();
$keysArr = array_merge($keysArr, $this->handleIn($this->separator, $result));
});
return collect($keysArr)->values()->unique()->sort()->all();
}
/**
* 重寫(xiě)匹配方法
* @param array $models
* @param Collection $results
* @param string $relation
* @return array
*/
public function match(array $models, Collection $results, $relation)
{
$dictionary = $this->buildDictionary($results);
// Once we have the dictionary we can simply spin through the parent models to
// link them up with their children using the keyed dictionary to make the
// matching very convenient and easy work. Then we'll just return them.
foreach ($models as $model) {
$keys = $model->getAttribute($this->localKey);
$keys = $this->handleIn($this->separator, $keys);
$keys = array_unique(array_filter($keys));
$type = 'one';
$relationResults = [];
foreach ($keys as $key) {
if (isset($dictionary[$key])) {
$temp = $this->getRelationValue($dictionary, $key, $type);
$relationResults[] = $temp;
}
}
$model->setRelation(
$relation, collect($relationResults)
);
}
return $models;
}
/**
* 自定義轉(zhuǎn)換方法
* @param $separator
* @param $keyString
* @return array
*/
private function handleIn($separator, $keyString)
{
$keys = is_array($keyString)?$keyString : explode($separator, $keyString);
$keys = array_unique($keys);
if ($this->strict === false)
return $keys;
array_walk($keys, function (&$value) {
$fun = $this->strict === true ? 'intval' : $this->strict;
$value = $fun($value);
});
return $keys;
}
}
修改App\Providers\AppServiceProvider文件志秃,
原理是利用宏指令增加 builder 方法
宏指令介紹:翻譯:神奇的 Laravel 宏指令(Macro)
宏指令內(nèi)容是參考 Illuminate\Database\Eloquent\Concerns\HasRelationships 類(lèi)里面的 hasMany 函數(shù)寫(xiě)的,最優(yōu)方案是把宏指令建給 Model 類(lèi)(因?yàn)?HasRelationships 是被 Model use 的)但 Model 類(lèi)不支持宏指令退而求其次建給了 \Illuminate\Database\Eloquent\Builder
public function boot()
{
$newRelatedInstance =function ($class,$connection)
{
return tap(new $class, function ($instance)use ($connection) {
if (! $instance->getConnectionName()) {
$instance->setConnection($connection);
}
});
};
\Illuminate\Database\Eloquent\Builder::macro('hasManyFromStr', function ($related, $foreignKey = null, $localKey = null, $separator = ',', $strict = false) use ($newRelatedInstance) {
$model = $this->getModel();
$instance = $newRelatedInstance($related,$model->getConnectionName());
$foreignKey = $foreignKey ?: $model->getForeignKey();
$localKey = $localKey ?: $model->getKeyName();
return new HasManyFromStr($instance->newQuery(), $model, $instance->getTable().'.'.$foreignKey, $localKey, $separator, $strict);
});
}
調(diào)用方法
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class MenuRole extends Model
{
protected $table='menu_role';
public function menus(){
return $this->hasManyFromStr(Menu::class,'id','menu_ids',',',true);
}
}
輸出結(jié)果
[
{
"id": 1,
"role_id": 1,
"menu_ids": "1,2,3,4",
"menus": [
{
"id": 1,
"name": "a"
},
{
"id": 2,
"name": "b"
},
{
"id": 3,
"name": "name2"
},
{
"id": 4,
"name": "name3"
}
]
},
{
"id": 2,
"role_id": 2,
"menu_ids": "2,3,4",
"menus": [
{
"id": 2,
"name": "b"
},
{
"id": 3,
"name": "name2"
},
{
"id": 4,
"name": "name3"
}
]
}
]