Laravel7 扩展 关联方式 (根据ids 字段 关联多条id记录)

使用实例:
一个课程有多个教师。表结构为课程 (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 \App\Restructure\Relations\HasManyFromStr ($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');
    }

————————————————
原文作者:yuntian
转自链接:https://learnku.com/articles/50612#reply203833
版权声明:著作权归作者所有。商业转载请联系作者获得授权,非商业转载请保留以上作者信息和原文链接。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值