猿问

Laravel,如何在控制器中获取会话数组并与模型进行比较

我有两个变量 id 和 distance 的 session Array,我想显示 DB 中的所有商店,其中 session 中的 ids 等于商店中的 ids 我还想显示每个商店的距离以及商店详细信息,请注意,我是 laravel 的新手, 谢谢


dd(session('storeinfo'));


 array:252 [▼

    0 => array:2 [▼

      "id" => 76

     "distance" => "3.23"

          ]

    1 => array:2 [▼

    "id" => 77

    "distance" => "7.09"

]

存储在数据库中:


 $stores = Storeinfo::all();


侃侃无极
浏览 183回答 2
2回答

富国沪深

$stores = [];$storeInfos = session('storeinfo');usort($storeInfos, function($a, $b) {&nbsp; &nbsp; if (!isset($a['distance'])) {return -1;}&nbsp; &nbsp; if (!isset($b['distance'])) {return 1;}&nbsp; &nbsp; if ($a['distance'] == $b['distance']) {&nbsp; &nbsp; &nbsp; &nbsp; return 0;&nbsp; &nbsp; }&nbsp; &nbsp; return ($a['distance'] < $b['distance']) ? -1 : 1;});foreach ($storeInfos as $storeInfo) {&nbsp; &nbsp; $store = Store::find($storeInfo['id']);&nbsp; &nbsp; if ($store) {&nbsp; &nbsp; &nbsp; &nbsp; $store->distance = $storeInfo['distance'];&nbsp; &nbsp; &nbsp; &nbsp; $stores[] = $store;&nbsp; &nbsp; }}return $stores;

慕后森

您可以使用whereIn()查询构建器中的函数来使用数据数组进行过滤。$stores = StoreInfo::whereIn(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 'id',&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; collect(session('storeinfo'))->map->id->toArray()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ->get()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; ->map(function($storeDetail) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //find the matching storeinfo from session.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $storeInfo = collect(session('storeinfo'))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;->firstWhere('id', $storeDetail->id);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // set distance&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return $storeDetail->distance = $storeInfo['distance'];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; });
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答