首页 > 解决方案 > 数组到字符串异常 Laravel

问题描述

CategoryApiController.php

    public function posts($id){<br>
        $category_data = Category::find($id);        
        $posts=$category_data->posts();
}



Category.php(模型)

 public function posts(){
        return Post::whereJsonContains('category_id',$this->attributes['id'])->get();



我正在尝试获取以 JSON 格式存储在 Category_id 中的特定类别的帖子。如果我将$this->attributes['id']替换为静态值'3',我会得到 m 正在寻找的数据,但我希望它是动态的。但是$this->attributes['id']将成功获取 ex (3) 的类别 ID,但它不接受作为参数并返回一个空数组。

这是我的表结构:

在此处输入图像描述

请帮帮我

标签: phparraysjsonlaravelexception

解决方案


你有几个问题。

  1. 您可能忘记添加数组转换。

https://laravel.com/docs/7.x/eloquent-mutators#array-and-json-casting

当你添加这个时,你应该得到这样的东西:

// Category.php

protected $casts = [
     'category_ids' => 'array'
];


// CategoryApiController@posts

$model->update(['category_ids' => [1, 2, 3]);
  1. 第二个问题是数据类型。您的数组存储字符串并且您传递一个数字,因此它不起作用。请注意,在第一点中,我向您展示了如何以整数保存。因此,如果您保存为整数,您的代码将在不更改此行的情况下运行。

Post::whereJsonContains('category_id', 1) // int

Post::whereJsonContains('category_id', '1') // 字符串

eg whereJsonContains('category_id', (string)$this->attributes['id'])// 传递字符串


推荐阅读