You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

108 lines
3.3 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

<?php
namespace App\Models;
class BaseForm extends SoftDeletesModel
{
protected $casts = [];
protected $appends = [];
public function __construct()
{
parent::__construct();
// 设置表
$this->setTable(request('table_name'));
// 设置关联关系
$this->relation();
// 设置json转数组字段
$this->casts = $this->jsonToArray();
}
/**
* 创建人关联
* @return \Illuminate\Database\Eloquent\Relations\HasOne
*/
public function admin()
{
return $this->hasOne(Admin::class, 'id', 'admin_id');
}
/**
* 关联创建部门
* @return \Illuminate\Database\Eloquent\Relations\HasOne
*/
public function department()
{
return $this->hasOne(Department::class, 'id', 'department_id');
}
/**
* 获取所有关联关系
* $raw=true返回原始设置false只输出关联关系名字数组
*/
public function allRelationFields($raw = false)
{
$customFormRelation = request('customForm')->relation;
if (empty($customFormRelation)) return [];
$customFormRelation = $customFormRelation->filter(function ($item) {
return !empty($item->link_table_name)
&& !empty($item->link_relation)
&& !empty($item->local_key)
&& !empty($item->foreign_key)
&& !empty($item->link_with_name);
});
// 输出原始数据
if ($raw) return $customFormRelation;
$customFormRelation = $customFormRelation->pluck('link_with_name')->toArray();
$baseRelation = ['admin', 'department'];
return array_merge($baseRelation, $customFormRelation);
}
/**
* 构建关联关系
*/
public function relation()
{
$customFormRelations = request('customForm')->relation;
if (empty($customFormRelations)) return true;
// 去除无效的关联
$customFormRelations = $customFormRelations->filter(function ($item) {
return !empty($item->link_table_name)
&& !empty($item->link_relation)
&& !empty($item->local_key)
&& !empty($item->foreign_key)
&& !empty($item->link_with_name);
});
foreach ($customFormRelations as $item) {
// 关联其他表数据
self::resolveRelationUsing($item->link_with_name, function ($fromModel) use ($item) {
if ($item->link_table_name == 'uploads') {
// 上传关联
$relatedModel = (new Upload())->newQuery();
} else {
$relatedModel = tableNameToModel($item->link_table_name);
}
return $fromModel->{$item->link_relation}($relatedModel, $this, $item->foreign_key, $item->local_key);
});
}
return true;
}
/**
* json字段转数组
*/
public function jsonToArray()
{
$customFormFields = request('customFormFields');
if (empty($customFormFields)) return [];
$casts = $customFormFields->whereIn('edit_input', CustomFormField::getJsonFieldType())
->pluck('field')
->mapWithKeys(function ($item) {
return [$item => 'json'];
})->toArray();
return $casts;
}
}