chengkun
2025-09-09 1ff9e27b020822168a95edd83be567e7153837f3
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
<?php
 
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2023 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
declare(strict_types=1);
 
namespace think\model\concern;
 
use think\db\BaseQuery as Query;
use think\db\exception\DbException as Exception;
use think\Model;
 
/**
 * 虚拟模型.
 */
trait Virtual
{
    /**
     * 获取当前模型的数据库查询对象
     *
     * @param array $scope 设置不使用的全局查询范围
     *
     * @return Query
     */
    public function db($scope = []): Query
    {
        throw new Exception('virtual model not support db query');
    }
 
    /**
     * 获取字段类型信息.
     *
     * @param string $field 字段名
     *
     * @return string|null
     */
    public function getFieldType(string $field)
    {
    }
 
    /**
     * 保存当前数据对象
     *
     * @param array|object  $data     数据
     * @param string $sequence 自增序列名
     *
     * @return bool
     */
    public function save(array|object $data = [], ?string $sequence = null): bool
    {
        if ($data instanceof Model) {
            $data = $data->getData();
        } elseif (is_object($data)) {
            $data = get_object_vars($data);
        }
 
        // 数据对象赋值
        $this->setAttrs($data);
 
        if ($this->isEmpty() || false === $this->trigger('BeforeWrite')) {
            return false;
        }
 
        // 写入回调
        $this->trigger('AfterWrite');
 
        $this->exists(true);
 
        return true;
    }
 
    /**
     * 删除当前的记录.
     *
     * @return bool
     */
    public function delete(): bool
    {
        if (!$this->isExists() || $this->isEmpty() || false === $this->trigger('BeforeDelete')) {
            return false;
        }
 
        // 关联删除
        if (!empty($this->relationWrite)) {
            $this->autoRelationDelete();
        }
 
        $this->trigger('AfterDelete');
 
        $this->exists(false);
 
        return true;
    }
}