【问题标题】:Laravel whereIn doesn't return all dataLaravel whereIn 不返回所有数据
【发布时间】:2021-07-14 10:05:02
【问题描述】:

我有以下数组(由explode方法创建)

["3D Printing"," 3D Architecture"," .NET Micro Framework"]

当我尝试将此标题与我的数据库匹配并获取每个标题的 id 时,我只得到第一项的 id。

["d21c6805-8780-4726-ba1d-12c9c3a28d0a"]

它应该返回这样的东西

["d21c6805-8780-4726-ba1d-12c9c3a28d0a", "1234...", "567...]

code

$a = $request->input('tags');
$b = str_replace(['[',']'], null, $a);
$comingTags = explode(',',$b);

$iddss = Tag::whereIn('title', $comingTags)->pluck('id');
return response()->json($iddss);

有什么建议吗?

PS:我最好的猜测是我的数组中的第 2 和第 3 项有空格,这可能会导致问题"{SPACE IS HERE}3D Architecture" 不确定是否是这个原因。

更新

我试过$b = str_replace([',', ' '], ['',''], $a);,但我现在得到的只是[]

更新 2

通过使用$b = str_replace(['[', ']', ' '], null, $a);,它确实从我的字符串中删除了空格,但也删除了我的标题单词之间的空格,因此3D Architecture 变为3DArchitecture,因此我也无法将标题与@987654332 中的数据库匹配@ 因为我的数据库标题是 3D Architecture,而我试图与之匹配的是 3DArchitecture

对此有何建议?

更新 3

$a = $request->input('tags');
// return 
"[3D Printing, 3D Architecture, .NET Micro Framework]"

.

$b = str_replace(['[',']'], null, $a);
// return
"3D Printing, 3D Architecture, .NET Micro Framework"

.

$comingTags = explode(',',$b);
// return
["3D Printing"," 3D Architecture"," .NET Micro Framework"]

【问题讨论】:

  • 空间可能是您的问题。修剪这些值,看看你的问题是否得到解决
  • @miladhedayatpoor 如何将,space 替换为null
  • 我认为它会对您有所帮助.. 自己没有尝试过,但在网上找到了。如果你想一次替换多个字符,试试这个:str_replace([ ' ' , ',' ], ' ', $string);
  • 试试$b = str_replace(['[', ']', ' '], null, $a);
  • @zahidhasanemon 是的,确实删除了第一个空格,但它也引起了另一个问题:) 现在我的标题词之间的空格也被删除了,它无法在Tag::whereIn('title', $comingTags)->pluck('id') 中匹配:D跨度>

标签: php laravel pluck


【解决方案1】:

要摆脱空白,您可以这样做 array_map('trim', $a); (credits)

whereIn 需要一个数组,所以这应该可以工作

$a = $request->input('tags');
$b = str_replace(['[',']'], null, $a);
$comingTags = array_map('trim', explode(',', $b));

$iddss = Tag::whereIn('title', $comingTags)->pluck('id');

return response()->json($iddss);

【讨论】:

  • 上面写着array_map(): Expected parameter 2 to be an array, string given
  • 仍然给出同样的错误,不知何故它无法识别数组中的$b
  • 你能用 $a 和 $b 的确切值更新你的问题吗?
  • 这可以完成工作:D $a = $request->input('tags'); $b = str_replace(['[',']'], null, $a); $comingTags = explode(',',$b); $comingTags2 = array_map('trim', $comingTags); $iddss = Tag::whereIn('title', $comingTags2)->pluck('id'); return response()->json($iddss);
  • 我会接受您的回答,因为 trim 成功了,但请使用我提供的有效代码解决方案更新您的答案。非常感谢。
猜你喜欢
  • 2021-03-19
  • 1970-01-01
  • 1970-01-01
  • 2019-08-14
  • 2020-04-24
  • 2014-05-10
  • 2021-09-06
  • 2020-03-04
  • 2017-05-30
相关资源
最近更新 更多