douben6670 2017-01-27 06:49
浏览 81

只能使用数组语法访问对象属性

Background

I have two methods that handle the import of an excel spread sheet, clean up fields (I.e. change "player_name" to "name"), filter out the invalid rows of data and the valid rows of data. If there is invalid data, it is returned to a Vue component, which gives the user the opportunity to correct the invalid data.

The initial submission is handled by AdminImportPlayersController@store and subsequent submissions (to fix invalid data) is handled by AdminImportFixedPlayersController@store.

Data is collected into a Collection upon post.

Problem

With the initial submission, handled by AdminImportPlayersController@store (actually importing the excel file), I can access the data within the Collection with object syntax (i.e. obj->prop). However, using basically the same code in the AdminImportFixedPlayersController@store controller (still have to refactor, probably abstract body of functionality into a Facade.) is treating the 'object' as an array. Obviously it is actually an array, but I have not worked out why this is..

Controllers are posted below.

Code

AdminImportPlayersController@store:

/**
 * Imports players from an excel spreadsheet.
 * Returns invalid players, if present.
 *
 * Teams are represented by their name in the submitted file.
 *
 * @param  App\HttpRequests\StoreImportPlayersFormRequest $request
 * @return Illuminate\Http\Response
 */
public function store(StoreImportPlayersFormRequest $request)
{
    $now = Carbon::now()->toW3cString();
    $fileName = 'players-import-' . $now . '.xls';

    // moving imported file to local storage
    $request->file('players')->move(storage_path('/import/excel/'), $fileName);

    // creating a Collection from the results returned from file
    $player_data = collect(Excel::load(storage_path('import/excel/') . $fileName)->get());

    // clean up data structure
    $player_data = $player_data->map(function ($player) {
        $player['name'] = $player->player_name;
        unset($player['player_name']);
        return $player;
    });

    // get all invalid entries
    $invalid_player_data = $player_data->filter(function ($player) {
        \Log::info($player);
        return ! Team::where('name', $player->team)->first() || $player->name == null;
    })->values();


    // get all valid entries
    $valid_player_data = $player_data->filter(function ($player) {
        return Team::where('name', $player->team)->first() && $player->name !== null;
    })->values();

    // save players
    $valid_player_data->each(function ($player) {
        $team = Team::where('name', $player->team)->first();
        $team->players()->attach(
            Player::create([
                'name' => $player->name,
                'temp' => 0,
            ])
        );
    });

    return response()->json(['invalid_player_data' => $invalid_player_data->all()], 200);
}

AdminImportFixedPlayersController@store:

/**
 * Stores fixed player data, after re-submission due to invalid data.
 * Returns invalid players, if still present.
 * Teams are represented by their id.
 *
 * @param  App\Http\Requests\StoreImportFixedPlayersFormRequest $request
 * @return Illuminate\Http\Response
 */
public function store(StoreImportFixedPlayersFormRequest $request)
{
    $player_data = collect($request->players);

    // get all invalid entries
    $invalid_player_data = $player_data->filter(function ($player) {
        return ! Team::where('id', $player['team'])->first() || $player['name'] == null;
    })->values();

    // get all valid entries
    $valid_player_data = $player_data->filter(function ($player) {
        return Team::where('id', $player['team'])->first() && $player['name'] !== null;
    })->values();

    // save players
    $valid_player_data->each(function ($player) {
        $team = Team::where('id', $player['team'])->first();
        $team->players()->attach(
            Player::create([
                'name' => $player['name'],
                'temp' => 0,
            ])
        );
    });

    return response()->json(['invalid_player_data' => $invalid_player_data->all()], 200);
}

Note that when saying something like

return ! Team::where('id', $player->team)->first() || $player->name == null; 

in AdminImportPlayersController (the controller that handles the initial importation), it is legal and no exceptions are thrown.

However, the same code, when used in AdminImportFixedPlayersController, throws an exception and I can only legally use the following syntax:

return ! Team::where('id', $player['team'])->first() || $player['name'] == null;

Sorry for the lengthy question, just like to be thorough!

Please ask for more information if needed.

I have logged out the values for the $player_data in both methods at various locations. The value of $player_data, in AdminImportFixedPlayersController, after being collected from the request is equal to something like:

[{"name": "ashley", "team" : 1}, ..., ...].

Why can't I access the properties of these objects, without using array-like syntax?

  • 写回答

1条回答 默认 最新

  • douzhuijing4911 2017-01-29 01:54
    关注

    Current Solution

    After creating a collection from $request->players

    $player_data = collect($request->players);
    

    I am mapping each Player to its own Collection and for each Player in $player_data, setting properties on each Player to equal the value of related data, accessed as a normal array: $player->name = $player['name'];.

    Solution:

       $player_data = collect($request->players);
    
        // turn each 'player' into a collection and create properties that are accessible via object->method notation
       $player_data = $player_data->map(function ($player) {
            $player = collect($player);
            $player->name = $player['name'];
            $player->team = $player['team'];
            return $player;
        });
    
    评论

报告相同问题?

悬赏问题

  • ¥15 一道python难题2
  • ¥15 一道python难题
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题
  • ¥15 教务系统账号被盗号如何追溯设备