Laravel Array和JSON Casting to Algolia

问题描述 投票:0回答:1

我试图通过toSearchableArray向Algolia发送一些数据。我存储在我的数据库中的任何字符串都是正常发送的,但是当我尝试推送嵌套的JSON数据时,我遇到了障碍 - 信息被发送为带有字符转义字符串的字符串。

这是我存储在我的表中的嵌套对象的示例(具有JSON数据类型的MySQL):

[
    {
        "id": 19, 
        "name": "Mathematics", 
        "short": "Math"
    }, 
    {
        "id": 23, 
        "name": "Science", 
        "short": "Science"
    }, 
    {
        "id": 14, 
        "name": "Health and Life Skills", 
        "short": "Health"
    }
]

我的模型看起来像这样:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Laravel\Scout\Searchable;

class Resource extends Model
{
    use Searchable;
    protected $primaryKey = 'objectID';

    public function toSearchableArray()
    {
        $data = $this->toArray();

        $data['grades'] = explode(';', $data['grades']);
        $data['units'] = explode(';', $data['units']);

        return $data;
    }
}

我得到一个如下所示的输出:

array:22 [
  "objectID" => 1
  "name" => "Resource #1"
  "slug" => "resource-1"
  "write_up" => """
    This is an example write up.
    """
  "author" => "johnny"
  "type_name" => "Lesson Plan"
  "language" => "English"
  "grades" => array:3 [
    0 => "Kindergarten"
    1 => "Grade 1"
    2 => "Grade 4"
  ]
  "subjects" => "[{"id": 19, "name": "Mathematics", "short": "Math"}, {"id": 23, "name": "Science", "short": "Science"}, {"id": 14, "name": "Health and Life Skills", "short": "Health"}]"
  "units" => array:2 [
    0 => "Unit A"
    1 => "Unit B"
  ]
  "main_image" => "https://dummyimage.com/250x325/000000/fff.png&text=Just+a+Test"
  "loves" => 88
  "downloads" => 280
  "created_at" => "2018-01-01 13:26:47"
  "updated_at" => "2018-01-02 10:10:32"
]

如您所见,'subject'属性存储为字符串。我知道在5.5中有属性转换(我正在运行5.5),但是我不太清楚如何在上面的工作中实现它们对Array&JSON Casting的示例。 https://laravel.com/docs/5.5/eloquent-mutators#attribute-casting

有人愿意给我看一个例子吗?

json laravel nested algolia
1个回答
11
投票

我依靠属性转换,在你的模型中添加一个$casts属性,它将自动完成。

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Laravel\Scout\Searchable;

class Resource extends Model
{
    use Searchable;
    protected $primaryKey = 'objectID';

    protected $casts = [
        'subjects' => 'array',
    ];

    public function toSearchableArray()
    {
        // Same function as you posted
    }
}

您也可以使用$data['subjects'] = json_decode($this->subjects, true);在toSearchableArray方法中手动执行此操作

我回答了其他帖子的更多细节:https://discourse.algolia.com/t/laravel-array-json-casting-to-algolia/4125/2

© www.soinside.com 2019 - 2024. All rights reserved.