Category (with description method on foreign Key categories_id)
CategoryDescription
The combo above is working via DB table categories WITH categories_description
Same for products
Product
ProductDescription (with description method on foreign Key products_id)
Now i created the model ProductsToCategories
Owning the table: products_to_categories
contains the columns: categories_id | products_id
My url can be the following and already working for the categories mysite.test/cPath=1_2_3
I get back the names and id's for all 3 categories.
Now i need to list the products assigned to categories_id = 3, or if i'm in ...cPath=1_2 for 2 ( if contain products or in cPath=1 if contain products......... i think you get the point).
What should be found via products_to_categories.
At this moment i'm stuck, as i can only find examples where the product is directly associated to the categories DB and not via a middle table products_to_categories.
So far i figured that Product can have many Category, and i also figured that ProductsToCategories can have Many Product.
But i'm getting a brainFreeze on this one, while i know it is something very simple as i try to avoid the N+1 scenario.
Hope someone can clear it up for me.
Thanks in advance!
(i keep learning)
@SilenceBringer
I think i explained it well?
The relationship should go via ProductsToCategories ( table: products_to_categories, columns : products_id | categories_id)
So if i'm on 3 cPath=4_67_3 i should call products_to_categories table and load all Products (products_id) related to category.categories_id: 3
I handle the cPath by explode it, i not worry for that.... an example with a static categories_id would be sufficient to get me on track.
$cPath = \Request::input('cPath');
PS: i think the relationship is between ProductsToCategory and Product ........... mmmm i'm getting smarter while answering.
I think like this:
I get the desired return from products_to_categories in the model Categories
I now need to do .................( i think)
a "belongsTo"................... not sure yet!
Or tell ProductsToCategories to return all products_id
like a
None of the above is good.
Now i understand, i think!
Took me a while.
PhpStorm and it's anoying 'Hints' helped me out.
class ProductsToCategories extends Model
{
use HasFactory;
protected $table = 'products_to_categories';
protected $with = [ 'products'];
public function products(){
return $this->belongsTo(Products::class, 'products_id');
}
}