postgresql Laravel 5.6.如何测试JSON/JSONb列

mfuanj7w  于 2023-05-22  发布在  PostgreSQL
关注(0)|答案(5)|浏览(97)

$this->assertDatabaseHas()不适用于JSON/JSONb列。
那么,如何在Laravel中测试这些类型的列呢?
目前,我有一个商店的行动。如何执行Assert,即保存了具有预定义值的特定列。
就像
['options->language', 'en']
不是一个选项,因为我有一个广泛的JSON与 meta的东西。
如何在DB中立即检查JSON

relj7zay

relj7zay1#

UPD
现在可以做like that
我已经用这个一行程序解决了它(根据你的模型/字段调整它)
$this->assertEquals($store->settings, Store::find($store->id)->settings);

xdnvmnnf

xdnvmnnf2#

Laravel 7+

不知道这个解决方案能用多久。
我找到了解决办法。忽略一些数据标签,一切都是可访问的,我只是在玩我的测试来弄清楚它。

/**
 * @test
 */
public function canUpdate()
{
    $authUser = UserFactory::createDefault();
    $this->actingAs($authUser);

    $generator = GeneratorFactory::createDefault();

    $request = [
        'json_field_one' => [
            'array-data',
            ['more-data' => 'cool'],
            'data' => 'some-data',
            'collection' => [
                ['key' => 'value'],
                'data' => 'some-more-data'
            ],
        ],
        'json_field_two' => [],
    ];

    $response = $this->putJson("/api/generators/{$generator->id}", $request);
    $response->assertOk();

    $this->assertDatabaseHas('generators', [
        'id' => $generator->id,
        'generator_set_id' => $generator->generatorSet->id,

        // Testing for json requires arrows for accessing the data
        // For Collection data, you should use numbers to access the indexes
        // Note:  Mysql dose not guarantee array order if i recall. Dont quote me on that but i'm pretty sure i read that somewhere.  But for testing this works
        'json_field_one->0' => 'array-data',
        'json_field_one->1->more-data' => 'cool',

        // to access properties just arrow over to the property name
        'json_field_one->data' => 'some-data',
        'json_field_one->collection->data' => 'some-more-data',

        // Nested Collection
        'json_field_one->collection->0->key' => 'value',

        // Janky way to test for empty array
        // Not really testing for empty
        // only that the 0 index is not set
        'json_field_two->0' => null,
    ]);
}
nxagd54h

nxagd54h3#

注意:以下解决方案在Laravel版本上测试:9.x和Postgres版本:12.x**,解决方案可能无法在较低版本的laravel上工作**

将json列Assert到数据库中有两个条件。

1.对象

考虑Object在数据库的json列中,如下所示:

"properties" => "{"attributes":{"id":1}}"

它可以Assert为

$this->assertDatabaseHas("table_name",[
    "properties->attributes->id"=>1
]);
2.数组

考虑array在json列中,如下所示:

"properties" => "[{"id":1},{"id":2}]"

它可以Assert为

$this->assertDatabaseHas("table_name",[
    "properties->0->id"=>1,
    "properties->1->id"=>2,
]);
qcuzuvrc

qcuzuvrc4#

如果要在数据库中Assert数组,可以使用如下方法:

$this->assertDatabaseHas(ModelSettings::class, ['settings->array[0]' => 'value'])
t2a7ltrp

t2a7ltrp5#

在值上使用json_encode对我来说很有效:

$this->assertDatabaseHas('users', [
    'name' => 'Gaurav',
    'attributes' => json_encode([
        'gender' => 'Male',
        'nationality' => 'Indian',
    ]),
]);

相关问题