美文网首页
laravel关联关系查询,ids字段逗号间隔

laravel关联关系查询,ids字段逗号间隔

作者: 耍帅oldboy | 来源:发表于2023-12-20 11:35 被阅读0次

实现方法添加类: App\Restructure\Relations\HasManyFromStr
用于处理关联方法
此类是参考 Illuminate\Database\Eloquent\Relations\HasMany 做的对应改动
代码如下

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;
    }
}

修改App\Providers\AppServiceProvider文件,
原理是利用宏指令增加 builder 方法
宏指令介绍:翻译:神奇的 Laravel 宏指令(Macro)
宏指令内容是参考 Illuminate\Database\Eloquent\Concerns\HasRelationships 类里面的 hasMany 函数写的,最优方案是把宏指令建给 Model 类(因为 HasRelationships 是被 Model use 的)但 Model 类不支持宏指令退而求其次建给了 \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);
        });
    }

调用方法

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);
  }
}

输出结果

[
{
"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"
}
]
}
]

相关文章

  • Laravel 简单查询

    记录使用laravel查询sql的记录 查询某字段中包含以逗号分隔的字符串的数据 原生sql laravel

  • laravel 关联模型使用 with 调数据时指定字段出错

    laravel 关联模型使用 with 调数据时指定字段必须包括 外键的字段 参考: laravel5.1 el...

  • TP3.2 LIKE 模糊查询

    比如查询ids字段(2,25,23,13,11,15);只查询23。 例如写法:like '%,23' or li...

  • 索引建立的条件

    主键自动建立唯一索引; 频繁作为查询条件的字段应该创建索引; 查询中与其他表有关联的字段,例如外键关系; 频繁更新...

  • mysql高级内容学习总结

    主键自动建立唯一索引 频繁作为查询条件的字段应该建立索引 查询中与其他表关联的字段,外键关系建立索引 频繁更新的字...

  • mysql-哪些些情况需要或者不需要创建索引

    哪些些情况需要创建索引 1、主键自动建立唯一索引2、频繁作为查询条件的字段3、查询中与其他表关联的字段,外键关系建...

  • MySQL索引失效

    哪些情况需要创建索引 主键自动建立唯一索引频繁作为查询条件的字段应该创建索引多表关联查询中,关联字段应该创建索引 ...

  • mysql学习之select

    查询记录 1.“*”表示将所有的字段都显示出来 2.用逗号分割,列出需要显示的字段 查询不重复的记录 条件查询 排...

  • SQL语法纠正

    执行顺序①from查询表②join关联表③on字段条件④where字段条件⑤group by分组字段⑥having...

  • Oracle数据库——多表查询

    一、关联查询 1.关联查询select 表1的字段名,表2的字段名 from 表1 [别名1],表2 [别名2] ...

网友评论

      本文标题:laravel关联关系查询,ids字段逗号间隔

      本文链接:https://www.haomeiwen.com/subject/pgbtndtx.html