:D
I can't make a Many to Many Relationships between two Laravel Sushi Models.
For example, I have two sushi models: Product and Category. I want to make a many-to-many relationship between them.
Model\Product.php
class Product extends Model
{
use Sushi;
protected $rows = [
[
'id' => 1,
'name' => 'Product 1',
],
[
'id' => 2,
'name' => 'Product 2',
],
];
/** @return BelongsToMany<Category> */
public function categories(): BelongsToMany
{
return $this->belongsToMany(Category::class);
}
Model\Category.php
class Category extends Model
{
use Sushi;
protected $rows = [
[
'id' => 10,
'name' => 'Category 1',
],
[
'id' => 11,
'name' => 'Category 2',
],
];
/** @return BelongsToMany<Product> */
public function products(): BelongsToMany
{
return $this->belongsToMany(Product::class);
}
}
If I try to load the values I get this error:
$product = Product::find(1);
$product->load('categories');
/*
Illuminate Database QueryException PHP 8.3.8 Laravel Framework 11.8.0
SQLSTATE[HY000]: General error: 1 no such table: category_product
*/
I understand that by default, Laravel wants this table for the "Many to Many Relationships", but: How could I get around having to create this table and have the data be static? Similar to Sushi's getRows() method.
I need it to allow me to put "static" data so that I can replace it with my real data source. I get the data from an external request and receive it in this format:
Product:
{
"id": 1,
"name": "Product 1",
"categories": [
10,
11
]
}
Category:
{
"id": 10,
"name": "Category 1",
"products": [
1,
2
]
}
Thanks in advance and best regards!
Test input
$product = Product::find(1);
$product->load('categories');
Expected output
{
"id": 1,
"name": "Product 1",
"categories": [
{
"id": 10,
"name": "Category 1"
}
]
}