首页 > 解决方案 > 我想存储数组中的数据,并且需要将这些实体的 id 存储在另一个数组中

问题描述

!!!更新 !!!

问题由我自己解决,更新后的工作代码如下

我正在尝试从$locations = "khulna, dhaka"Laravel 中的数组存储数据。但是位置表中的位置不应重复。稍后我需要这些位置的 ID(如果它们已经在表中或新插入的表中)在另一个数组中,以便我可以将它们附加到用户。

public function addUser(Request $request)
    {
        $locations = $request->location;

        // need to store in the table without duplicating
        // Update - Now I am able to store data without duplicating
        foreach($locations = explode(',', $locations) as $location)
        {
            Location::firstOrCreate([
                'name'  => $location,
                'slug'  => Str::slug($location),
            ]);
        }

        // need the IDs of the locations in another array - (Solved) 
        foreach($locations as $location)
        {
            $location = Location::where('slug', Str::slug($location))->first();
            $location_ids[] = $location->id;
        } 

            $user = User::create([
                'name'              => $request->name,
                'email'             => $request->email,
            ]);

            // Because I need to attach those locations with user
            $user->locations()->attach($location_ids);


        return redirect('users');
    }

标签: arrayslaravel-5eloquent

解决方案


推荐阅读