在laravel中使用pluck()辅助函数

时间:2017-11-23 17:36:03

标签: laravel laravel-5.5 laravel-eloquent laravel-collection

我正在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);

我还在学习收藏,任何建议都表示赞赏。感谢

2 个答案:

答案 0 :(得分:1)

来自$request(表单)的数据不是一个集合。它是一个阵列。如果你需要它是集合,你应该先将它转换为集合。

<强> PS 即可。如果您在单个方法中有多个数据库操作,那么进行数据库事务会很好。

\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); 
});

答案 1 :(得分:1)

  

我只想通过laravel collection

从用户数组中获取值键

然后使用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
});