93 lines
2.0 KiB
PHP
93 lines
2.0 KiB
PHP
<?php
|
||
|
||
namespace app\common\model;
|
||
|
||
use Illuminate\Database\Eloquent\SoftDeletes;
|
||
use support\Model;
|
||
|
||
class SysDict extends Model
|
||
{
|
||
use SoftDeletes;
|
||
|
||
/**
|
||
* The connection name for the model.
|
||
*
|
||
* @var string|null
|
||
*/
|
||
protected $connection = 'mysql';
|
||
|
||
/**
|
||
* The table associated with the model.
|
||
*
|
||
* @var string
|
||
*/
|
||
protected $table = 'sys_dict';
|
||
|
||
/**
|
||
* The primary key associated with the table.
|
||
*
|
||
* @var string
|
||
*/
|
||
protected $primaryKey = 'id';
|
||
|
||
/**
|
||
* Indicates if the model should be timestamped.
|
||
*
|
||
* @var bool
|
||
*/
|
||
public $timestamps = true;
|
||
|
||
|
||
protected $dateFormat = 'U';
|
||
|
||
/**
|
||
* 允许自动填充模型字段
|
||
*/
|
||
protected $fillable = ['id', 'category_id', 'dict_name', 'dict_code', 'description', 'status', 'created_at', 'updated_at', 'deleted_at'];
|
||
|
||
/**
|
||
* 不允许自动填充模型字段
|
||
*/
|
||
protected $guarded = [];
|
||
|
||
|
||
// 定义与 SysDictItem 的一对多关系
|
||
public function sysDictItem()
|
||
{
|
||
return $this->hasMany(SysDictItem::class, 'dict_id', 'id');
|
||
}
|
||
|
||
|
||
public function category()
|
||
{
|
||
return $this->belongsTo(SysDictCategory::class, 'category_id', 'id');
|
||
}
|
||
|
||
/**
|
||
* 一个字典有多个字典项
|
||
*/
|
||
public function items()
|
||
{
|
||
return $this->hasMany(SysDictItem::class, 'dict_id', 'id');
|
||
}
|
||
|
||
/**
|
||
* 通过 dict_code 快速获取所有 item_value
|
||
*/
|
||
public function scopeGetItemValuesByCode($query, $dictCode)
|
||
{
|
||
return $query->where('dict_code', $dictCode)
|
||
->with('items') // 预加载关联项
|
||
->first()?->items->pluck('item_value'); // 返回 item_value 数组
|
||
}
|
||
|
||
/**
|
||
* 通过 dict_code 获取完整字典项(含 label + value)
|
||
*/
|
||
public function scopeGetItemsByCode($query, $dictCode)
|
||
{
|
||
return $query->where('dict_code', $dictCode)
|
||
->with('items')
|
||
->first()?->items;
|
||
}
|
||
} |