Laravel7 擴充套件 關聯方式 (根據ids 欄位 關聯多條id記錄)

yuntian發表於2020-10-13

使用例項:
一個課程有多個教師。表結構為課程(course)表中有teacher_ids欄位 儲存,隔開的多個教師(teacher)id
實現方法新增類: App\Restructure\Relations\HasManyFromStr
用於處理關聯方法
此類是參考Illuminate\Database\Eloquent\Relations\HasMany做的對應改動
程式碼如下

<?php
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; //元素執行函式 true 代表轉為int
        parent::__construct($query, $parent, $foreignKey, $localKey);
    }

    /**
     * 重寫獲取單個模型建方法
     */
    public function addConstraints()
    {
        if (static::$constraints) {
            $this->query->whereIn($this->foreignKey, $this->handleIn($this->separator, $this->getParentKey()));

            $this->query->whereNotNull($this->foreignKey);
        }
    }

    /**
     * 重寫獲取所有主鍵方法.
     *
     * @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();
    }


    /**
     * 重寫匹配方法
     * @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;
    }


    /**
     * 自定義轉換方法
     * @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;
    }
}

找一個已註冊的服務容器在boot中新增如下程式碼(比如App\Providers\AppServiceProvider)

$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 \Illuminate\Database\Eloquent\Relations\HasMany($instance->newQuery(), $model, $instance->getTable().'.'.$foreignKey, $localKey, $separator, $strict);
        });

原理是利用巨集指令增加builder方法
巨集指令介紹:翻譯:神奇的 Laravel 巨集指令(Macro)
巨集指令內容是參考 Illuminate\Database\Eloquent\Concerns\HasRelationships類裡面的hasMany函式寫的,最優方案是把巨集指令建給Model類(因為HasRelationships是被Model use的)但Model類不支援巨集指令退而求其次建給了\Illuminate\Database\Eloquent\Builder

呼叫程式碼例項
在課程Model中新增

//hasManyFromStr() 接收五個引數 
//關聯表類名 外來鍵 本地建 分隔符(預設為逗號) 對欄位分隔後執行的函式(false(不執行)/true(轉換為int)/str函式名  預設為false)
    public function teacher()
    {
        return $this->hasManyFromStr(Teacher::class,'id','teacher_ids');
    }
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章