@@ -57,7 +57,7 @@ public function __construct(?Model $model = null, bool $with = false)
5757 public function initData (bool $ relation = true )
5858 {
5959 // 获取实体属性
60- $ properties = $ this ->getEntityProperties ();
60+ $ properties = $ this ->getEntityPropertiesMap ();
6161 $ data = $ this ->model ()->getData ();
6262 foreach ($ properties as $ key => $ field ) {
6363 if (!$ relation ) {
@@ -126,21 +126,35 @@ private function fetchViewAttr(string $field)
126126 * @return array
127127 */
128128 private function getEntityProperties (): array
129+ {
130+ $ reflection = new ReflectionClass ($ this );
131+ $ properties = [];
132+ foreach ($ reflection ->getProperties (ReflectionProperty::IS_PUBLIC ) as $ property ) {
133+ $ properties [] = $ property ->getName ();
134+ }
135+ return $ properties ;
136+ }
137+
138+ /**
139+ * 获取包含映射关系的实体属性列表.
140+ *
141+ * @return array
142+ */
143+ private function getEntityPropertiesMap (): array
129144 {
130145 $ properties = $ this ->getOption ('view_properties ' );
131146 if (empty ($ properties )) {
132- $ reflection = new ReflectionClass ( $ this );
147+ $ fields = $ this -> getEntityProperties ( );
133148 $ mapping = $ this ->getOption ('viewMapping ' , []);
134149 $ properties = [];
135-
136- foreach ($ reflection ->getProperties (ReflectionProperty::IS_PUBLIC ) as $ property ) {
137- $ field = $ property ->getName ();
150+ foreach ($ fields as $ field ) {
138151 if (isset ($ mapping [$ field ])) {
139152 $ properties [$ field ] = $ mapping [$ field ];
140153 } else {
141154 $ properties [] = $ field ;
142155 }
143156 }
157+
144158 $ this ->setOption ('view_properties ' , $ properties );
145159 }
146160
@@ -163,17 +177,31 @@ public function toArray(): array
163177 return $ data ;
164178 }
165179
180+ /**
181+ * 设置视图模型数据
182+ *
183+ * @param array $data 数据
184+ * @return $this
185+ */
186+ public function data (array $ data )
187+ {
188+ // 数据验证
189+ $ data = $ this ->validate ($ data );
190+ foreach ($ this ->getEntityProperties () as $ field ) {
191+ $ this ->$ field = $ data [$ field ] ?? null ;
192+ }
193+ return $ this ;
194+ }
195+
166196 /**
167197 * 获取视图模型数据
168198 *
169199 * @return array
170200 */
171201 protected function getData (): array
172202 {
173- $ reflection = new ReflectionClass ($ this );
174- $ data = [];
175- foreach ($ reflection ->getProperties (ReflectionProperty::IS_PUBLIC ) as $ property ) {
176- $ field = $ property ->getName ();
203+ $ data = [];
204+ foreach ($ this ->getEntityProperties () as $ field ) {
177205 $ data [$ field ] = $ this ->$ field ;
178206 }
179207 return $ data ;
@@ -299,7 +327,7 @@ public function bindRelationAttr($model, $bind, $relation)
299327 protected function convertData (): array
300328 {
301329 // 获取实体属性
302- $ properties = $ this ->getEntityProperties ();
330+ $ properties = $ this ->getEntityPropertiesMap ();
303331 $ mapping = $ this ->getOption ('autoMappingAlias ' , []);
304332 $ data = $ this ->getData ();
305333 $ item = [];
0 commit comments