예제 #1
0
func (ar *ActiveRecord) FindAll(rowsSlicePtr interface{}) error {
	ar.ScanPK(rowsSlicePtr)
	sliceValue := reflect.Indirect(reflect.ValueOf(rowsSlicePtr))
	if sliceValue.Kind() != reflect.Slice {
		return errors.New("needs a pointer to a slice")
	}

	sliceElementType := sliceValue.Type().Elem()
	st := utils.Struct{reflect.New(sliceElementType).Interface()}
	var keys []string
	results := st.StructToSnakeKeyMap()
	if ar.TableName == "" {
		ar.TableName = ar.getTableName(rowsSlicePtr)
	}

	for key, _ := range results {
		keys = append(keys, key)
	}

	ar.ColumnStr = strings.Join(keys, ", ")
	resultsSlice, err := ar.FindMap()
	if err != nil {
		return err
	}

	for _, results := range resultsSlice {
		newValue := reflect.New(sliceElementType)
		utils.M(results).MapToStruct(newValue.Interface())
		sliceValue.Set(reflect.Append(sliceValue, reflect.Indirect(reflect.ValueOf(newValue.Interface()))))
	}

	return nil
}
예제 #2
0
func (ar *ActiveRecord) Find(output interface{}) error {
	st := utils.Struct{output}
	ar.ScanPK(output)
	var keys []string
	results := st.StructToSnakeKeyMap()
	if ar.TableName == "" {
		ar.TableName = ar.getTableName(output)
	}

	for key, _ := range results {
		keys = append(keys, key)
	}

	ar.ColumnStr = strings.Join(keys, ", ")
	ar.Limit(1)
	resultsSlice, err := ar.FindMap()
	if err != nil {
		return err
	}

	if len(resultsSlice) == 0 {
		return nil
	} else if len(resultsSlice) == 1 {
		results := resultsSlice[0]
		utils.M(results).MapToStruct(output)
	} else {
		return errors.New("More Then One Records")
	}

	return nil
}