当前位置:网站首页>Read multiple associations from a field using delimiters in laravel
Read multiple associations from a field using delimiters in laravel
2022-06-25 19:16:00 【kankan231】
In database design , It is often useful to store information separated by commas
In our business scenario , Will design a lot For example, label records for orders or users , One to many relationship between user and tag If you use a single table to maintain label relationships When the actual business scenario is not particularly complex , It seems a little superfluous , At this time, a field is often used to separate the record label or other information with special characters ;
stay laravel In frame , In this scene , If the echo of data is join Or one to many association , It is not suitable for data query, echo and data duplication elimination , If there is a single field , Special associations separated by special characters are good
Below we give a description of the single field , According to the special separator character , Load the associated code implementation
Define a class HasManyFromStr.php
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasOneOrMany;
class HasManyFromStr extends HasOneOrMany
{
protected $separator = ',';
public function __construct(Builder $query, Model $parent, string $foreignKey, string $localKey, $separator)
{
parent::__construct($query, $parent, $foreignKey, $localKey);
$this->separator = $separator;
}
/**
* Get the results of the relationship.
*
* @return mixed
*/
public function getResults()
{
return ! is_null($this->getParentKey())
? $this->query->get()
: $this->related->newCollection();
}
/**
* Initialize the relation on a set of models.
*
* @param array $models
* @param string $relation
* @return array
*/
public function initRelation(array $models, $relation)
{
foreach ($models as $model) {
$model->setRelation($relation, $this->related->newCollection());
}
return $models;
}
/**
* Rewrite matching method
* @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 = explode($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;
}
/**
* Get all of the primary keys for an array of models.
*
* @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, explode(',', $result));
});
return collect($keysArr)->values()->filter()->unique()->sort()->all();
}
}
In the model of the base class , Inherit lavarel Model class , Implement the following methods baseModel.php
/**
* Define a one-to-many relationship From a field with comma or other separator.
*
* @param $related
* @param null $foreignKey
* @param null $localKey
* @param string $separator
* @return HasManyFromStr
*/
public function hasManyFromStr($related, $foreignKey = null, $localKey = null, $separator = ',')
{
$instance = $this->newRelatedInstance($related);
$foreignKey = $foreignKey ?: $this->getForeignKey();
$localKey = $localKey ?: $this->getKeyName();
return $this->newHasManyFromStr(
$instance->newQuery(), $this, $instance->getTable().'.'.$foreignKey, $localKey, $separator
);
}
/**
* Instantiate a new HasManyFromStr relationship.
*
* @param Builder $query
* @param Model $parent
* @param $foreignKey
* @param $localKey
* @param string $separator
* @return HasManyFromStr
*/
protected function newHasManyFromStr(Builder $query, Model $parent, $foreignKey, $localKey, $separator = ',')
{
return new HasManyFromStr($query, $parent, $foreignKey, $localKey, $separator);
}
Actual model classes ( Inherit the above model base class ) in The association of is defined as follows :
public function tagList()
{
return $this->hasManyFromStr(ErpTagModel::class, 'id', 'tag_id');
}
author :linlancer
link :https://www.jianshu.com/p/882aa5eec382
边栏推荐
- Idea common plug-ins
- 2020-12-09 laravel . Env file loading mechanism process
- 广州华锐互动打造VR展厅全景在线虚拟展厅
- 1、 Hikaricp source code analysis of connection acquisition process I
- User management and permissions
- 一、HikariCP获取连接流程源码分析一
- TCP/IP 测试题(三)
- Electronic basic project construction & communication between main thread and rendering thread
- Connecting PHP to MySQL instances in the lamp environment of alicloud's liunx system
- 【历史上的今天】6 月 25 日:笔记本之父诞生;Windows 98 发布;通用产品代码首次商用
猜你喜欢

On location and scale in CNN

What is an operator?

Vulnhub range - correlation:2

如何快速关闭8080端口

Ali vision AI training camp-day01

PHP synchronizes website content to hundreds of websites to improve SEO ranking

Record Baidu search optimization thinking analysis

Mail monitoring cloud script execution progress

Tiger Dao VC products are officially launched, a powerful supplement to seektiger ecology

Trend ea- fixed stop loss and profit per order
随机推荐
Ali visual AI training camp -day03- construction of electronic photo album (face and expression recognition)
Oriental Wealth function (the most complete edition of Childe Yong)
JVM | runtime data area (heap space)
Electronic basic project construction & communication between main thread and rendering thread
Mail monitoring cloud script execution progress
Does GoogleSEO need to change the friend chain? (e6zzseo)
mysql事务讲解
Elastic high-performance computing on the cloud supports the rapid development of the life science industry, reducing costs and increasing efficiency
IDEA常用插件
3、 Hikaricp source code analysis of connection acquisition process III
mysql my. Understanding CNF depends on configuration
Lilda Bluetooth air conditioning receiver helps create a more comfortable road life
Analysis on China's aluminum foil output, trade and enterprise leading operation in 2021: dongyangguang aluminum foil output is stable [figure]
PHP database connection version1.1
请问通达信开户安全吗?
PostgreSQL change table owner
In 2021, China's private equity market is growing, and the scale of private equity fund management reaches 19.78 trillion yuan [figure]
[today in history] June 25: the father of notebook was born; Windows 98 release; First commercial use of generic product code
Analysis on development scale and development trend of China's night economy industry in 2021 [figure]
网络安全检测与防范 练习题(三)