【问题标题】:Laravel Stuck with returning a json request -> Integer Array -> receiving Eloquent ModelsLaravel 卡在返回一个 json 请求 -> 整数数组 -> 接收 Eloquent 模型
【发布时间】:2017-07-25 18:03:06
【问题描述】:

我试图回答一个 JSON 请求,返回请求中提供的 id 上的 Laravel-Models。

这是我的 - JSON 请求 { "places": [1,2, 3, 4, 5] }

首先我将它转换为一个数组:

将请求转换为数组

$array = $request->places;

输出:

array:5 [
  0 => 1
  1 => 2
  2 => 3
  3 => 4
  4 => 5
]

这就是我接收所有模型的方式(在此示例中,1,2 是手动输入的 id: 获取所有地点

$posts = Post::whereIn('place_id',[1,2] )->get();

我的问题,占位符 [1,2] 只允许整数列表。但我无法像这样将我的数组转换为占位符变量。

$posts = Post::whereIn('place_id',[$request] )->get();

如果我将数组放入一个字符串变量中,假设:$request = "1,2,3,4,5" 那么,我只会从第一个值(在本例中为数字 1)接收模型。

有什么方法可以转换我的 JSON 请求以接收所有 Laravel 模型?

任何帮助将不胜感激, 干杯塞巴斯蒂安

【问题讨论】:

  • 试试$posts = Post::whereIn('place_id', array_values($request->places) )->get();
  • 你不就做$posts = Post::whereIn("place_id", $array)->get();吗?
  • 不幸的是,有一个“array_values() 期望参数 1 是数组,给定 null”错误

标签: php arrays json laravel laravel-eloquent


【解决方案1】:

你应该试试这样的。

$posts = Post::whereIn('place_id', $request->request->get('places', []))->get();

当你的请求正文是。

{
    "places": [1, 2, 3, 4, 5]
}

【讨论】:

  • 不幸的是,有一个 foreach() 错误:“为 foreach() 提供的参数无效”
  • @Sebastian 您是否使用Content-Type: application/json 标头发送请求?
  • 是的,我在我的 Header 中使用 Content-Type application/json & Accept application/json。
  • 您的请求似乎有问题。您能否在控制器操作中提供dd($request->request->all()) 函数调用的输出?
  • 抱歉回复晚了,array:1 [ "place_id" => array:3 [ 0 => "1" 1 => "2" 2 => "3" ] ]
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-03-14
  • 1970-01-01
  • 2019-02-13
  • 2023-04-01
  • 2015-08-27
  • 1970-01-01
  • 2013-02-24
相关资源
最近更新 更多