0

我正在构建一个小型应用程序,在该应用程序中laravel 5.5,我可以从以下格式的表单中获取包含多个用户的信息列表:

{
    "name":"Test",
    "description":"Test the description",
    "users":[
        {
            "value":"XYZabc123",
            "name":"Nitish Kumar",
            "email":"nitishkumar@noeticitservices.com"
        },
        {
            "value":"MFnjMdNz2DIzMJJS",
            "name":"Rajesh Kumar Sinha",
            "email":"rajesh@noeticitservices.com"
        }
    ]
}

我只想通过这样的value方式从用户数组中获取密钥:laravel collection

$userIds = $request->users->pluck('value');

这样我就可以将它们放入查询中:

$user = User::all()->whereIn('unique_id', $userIds);

可能是我做错了大部分事情,但我的主要动机是使用laravel collectionhelper功能并为此制作更清晰的代码:

$teamData['name'] = $request->name;
$teamData['description'] = $request->description;
$teamData['unique_id'] = str_random();

$users = $request->users;

$team = Team::create($teamData);

if($team)
{
    $userIds = [];

    foreach ($users as $user)
    {
        $getUser = User::where('unique_id', $user['value'])->get()->first();
        $userIds [] = $getUser->id;
    }

    $team->users()->attach($userIds);

    return response()->json(['message' => 'Created Successfully'], 200);
}

return response()->json(['message' => 'Something went wrong'], 500);

我还在学习收藏,任何建议都值得赞赏。谢谢

4

2 回答 2

1

来自$request(表单)的数据不是一个集合。这是一个数组。如果您需要它作为收藏,您应该先将其转换为收藏。

附言。如果您在单个方法中有多个 DB 操作,最好有 DB 事务。

\DB::transaction(function () use ($request) {
    // convert it to collection
    $users = collect($request->users);

    $team = Team::create([
        'name' => $request->name,
        'description' => $request->description,
        'unique_id' => str_random(),
    ]);

    $team->users()->attach($users->pluck('value')->toArray()); 
});

// HTTP Created is 201 not 200
return response()->json(['message' => 'Created Successfully'], 201);

或者你需要这样的东西:

return \DB::transaction(function () use ($request) {
    $users = collect($request->users);

    $team = Team::create([
        'name' => $request->name,
        'description' => $request->description,
        'unique_id' => str_random(),
    ]);

    $team->users()->attach($users->pluck('value')->toArray());

    return response()->json([
        'message' => 'Created Successfully',
        'data' => $team,
    ], 201); 
});
于 2017-11-23T20:20:49.290 回答
1

我只想通过 laravel 集合从用户数组中获取值键

只需使用map

$userIds = $request->users->map(function($user) {
    return $user->value;  // or $user['value'] ? not sure if this is an array
});

编辑:

如果$request->users不是集合,请在调用 map 之前将其设为一个:

$users = collect($request->users);

$userIds = $users->map(function($user) {
    return $user->value;  // or $user['value'] ? not sure if this is an array
});
于 2017-11-23T20:40:25.487 回答