【问题标题】:Array to String Exception Laravel数组到字符串异常 Laravel
【发布时间】:2020-11-04 18:55:54
【问题描述】:

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,但它不接受作为参数并返回一个空数组。

这是我的表结构:

请帮帮我

【问题讨论】:

  • 您好,欢迎您。您可能想重新访问您的帖子并在标记上做一些工作,因为目前很难阅读适当的格式和拼写错误。一篇好的帖子可能会产生比当前状态更多的答案。从我所看到的我想知道你试图让它发挥作用?

标签: php arrays json laravel exception


【解决方案1】:

你有一些问题。

  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') // 字符串

例如whereJsonContains('category_id', (string)$this-&gt;attributes['id']) // 传递字符串

【讨论】:

    猜你喜欢
    • 2016-10-18
    • 1970-01-01
    • 2021-08-24
    • 2021-09-22
    • 2016-07-28
    • 2016-06-29
    • 1970-01-01
    • 1970-01-01
    • 2017-05-22
    相关资源
    最近更新 更多