I am new to Laravel/Lumen. I am writing some API by using Lumen. Now I need some help on join table eloquent.
Here is my table structure,
catalog Table
| id | catalog_name | about_catalog | image |
product Table
| id | catalog_id | category_id | product_name | image |
category Table
| id | category_name | about_category |
I have the following models
Catalog Model
class Catalog extends Model
{
protected $table = 'catalog';
protected $fillable = [
'catalog_name',
'about_catalog',
'image'
];
protected $hidden = [
'created_at',
'updated_at',
'user_id'
];
public function catagories()
{
return $this->hasOneThrough(Category::class, Product::class, 'catalog_id', 'id', 'id', 'category_id')->with('products');
}
}
Product Model
class Product extends Model
{
public $timestamps = false;
protected $table = 'product';
protected $fillable = [
'catalog_id',
'category_id'
'product_name',
'image',
'status'
];
protected $hidden = [
'updated_at'
];
}
Category Model
class Category extends Model
{
protected $table = "category";
protected $fillable = [
'category_name',
'about_category'
];
protected $hidden = [
'created_at',
'updated_at'
'laravel_through_key'
];
function products()
{
return $this->hasMany(Product::class, 'id');
}
}
I need data as follows
"data": [
{
"id": 5,
"catalog_name": "Catalog Name"
"about_catalog": "About Catalog",
"image": ""
"categories": [{
"id": 1,
"category_name": "Test",
"products": [{
"id":1,
"....":"...."
}]
}]
}
]
Your help is appreciated, thanks a lot in advance.
CodePudding user response:
This is quite tricky.
You can get your desired output if your relationship is like this: Catalog has many Category, Category has many Product
Catalog model
public function categories(){
return $this->hasMany(Category::class);
}
Category model
public function products(){
return $this->hasMany(Product::class);
}
On your controller you can get the data like this
Catalog::with('categories.products')->get();
In this case you should move your catalog_id to your categories table. Hope this helps
CodePudding user response:
See your table structure is wrong there is no category reference in your catalog table so you can't fetch data of category you have foreign keys in product table so the data you want for that you have to add reference of category in catalog table then after from catalog to you can fetch categories and then you can fetch products hope you understood