I need help with hasManyThroughJson
Closed this issue · 1 comments
Greetings @staudenmeir, first if all, I love this package. it helps us properly use Json fields.
I am struggling with a relationship between categories and varieties through products.
See, a Product may belong to several categories, for that I use the field products.prodCategory:
Schema::create('products', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->foreignUuid('sellerId')->references('id')->on('sellers')->constrained()->cascadeOnDelete();
$table->string('productName');
$table->text('productDesc')->nullable();
$table->string('productImage')->nullable()->default('defaultproduct.png');
$table->json('prodCategory')->nullable();
$table->timestamps();
$table->softDeletes($column = 'deleted_at', $precision = 0);
});
Categories is as follows:
Schema::create('categories', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->string('name');
$table->boolean('isGeneral')->default(true);
$table->uuid('sellerId')->nullable();
$table->string('imageUrl')->default('defaultcategory.png');
$table->timestamps();
$table->softDeletes($column = 'deleted_at', $precision = 0);
});
}
and a product can have many varieties:
Schema::create('varieties', function (Blueprint $table) {
$table->uuid('id')->primary();
$table->string('name');
$table->text('description')->nullable();
$table->integer('price');
$table->foreignUuid('productId')->references('id')->on('products')->constrained()->cascadeOnDelete();
$table->boolean('isActive')->default(true);
$table->uuid('discountId')->nullable();
//$table->foreignUuid('discountId')->references('id')->on('discounts');
$table->timestamps();
});
now, I' able to list products with its categories and varieties with this relationship:
public function varieties() {
return $this->hasMany(Variety::class, 'productId', 'id');
}
public function categories() {
return $this->belongsToJson(Category::class,'prodCategory', 'id');
}
so far is working great, now I want to list categories with it products and of course, retrieve all varieties of said product and the relationships at the category model are like this:
public function product() {
return $this->hasManyJson(Product::class, 'prodCategory', 'id' );
}
public function varieties() {
return $this->hasManyThroughJson(Variety::class, Product::class, new JsonKey('id->prodCategory'));
}
when I run the API, i get the following message:
Error: Class "App\Models\JsonKey" not found in file ...\app\Models\Category.php on line 48
Line 48 being
return $this->hasManyThroughJson(Variety::class, Product::class, new JsonKey('id->prodCategory'));
can you please, please, at least point me in the right direction? I've been racking my brain for 3 days with no luck.
Thank you!
You need to import the JsonKey
class:
use Staudenmeir\EloquentJsonRelations\JsonKey;
class Category extends Model
{
//
}
I'll clarify that in the README.