php - 数组到字符串异常 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,但它不接受作为参数并返回一个空数组。
这是我的表结构:
请帮帮我
解决方案
你有几个问题。
- 您可能忘记添加数组转换。
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]);
- 第二个问题是数据类型。您的数组存储字符串并且您传递一个数字,因此它不起作用。请注意,在第一点中,我向您展示了如何以整数保存。因此,如果您保存为整数,您的代码将在不更改此行的情况下运行。
Post::whereJsonContains('category_id', 1) // int
Post::whereJsonContains('category_id', '1') // 字符串
eg whereJsonContains('category_id', (string)$this->attributes['id'])
// 传递字符串
推荐阅读
- vba - VBA - 根据单元格值插入星号
- html - 如何阻止div移动到右下角
- java - 制作一个迭代的多线程方法
- c++ - 在一个可简单复制的结构中,是否应该实现移动语义?
- selenium - Selenium - 将页面移到前面
- qt - 如何在 Qt creator 中读取服务器发送的访问令牌?
- c# - 在 System.Controls.Image 中渲染画布
- javascript - (D3js) 分层 Canvas 和 SVG 在本地与 JSFiddle 中生成不同的事件
- spring - 具有多个实例和粘性会话的 Spring Cloud Gateway 路由
- image - 检查图像是否已加载到 Flutter 中的 Image.network 小部件中