arrays - 我想存储数组中的数据,并且需要将这些实体的 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');
}
解决方案
推荐阅读
- xamarin.android - ASP.Net MVC 的 Azure B2C 应用程序注册也可以与 Xamarin IOS 和 Android 应用程序一起使用吗
- html - 为什么我的引导切换器不切换?
- ios - 应用程序被杀死时的静默通知问题
- c# - 使用来自不同表单的按钮在 a 上创建按钮
- coinbase-api - Coinbase API getBalance 忽略 ETC 货币
- azure - 天蓝色数据工厂 BlobEventsTrigger:以编程方式设置“高级过滤器”
- javascript - JIMP 图像合成未渲染
- flutter - 如何使用ffmpeg将视频录制限制在一定的时间范围内?
- android - Kotlin:没有设置 NavController
- python - Matplotlib - AttributeError:模块'sip'没有属性'setapi'