Search code examples
jsonlaraveleloquent-relationship

Laravel Relation on Json Array


i have relation b/w product categories and model where in model i have product_categories_id where i will save ["product_categories_id1","product_categories_id2"] so i have seen this https://github.com/staudenmeir/eloquent-json-relations and used like this in Models.php

use \Staudenmeir\EloquentJsonRelations\HasJsonRelationships;
public function category()
        {
            return $this->belongsToJson(ProductCategory::class, 'product_category_id');
        }

but did'nt get the expected result


Solution

  • Define the field type in model and try it. Also please make sure the array should not have the key.

    protected $casts = [
           'product_category_id' => 'json',
        ];