Laravel: Products,Categories and SubCategories! (Relation ships)
Here i may help u with this!
First , you can use only one table for categories and subcategory!
You can make this:
|---------------------------------------
|id| |parent_id| |name| |slug|
|1 | | (NULL) | Electronics | electronics
|2 | | 1 | Phones | phones
Now category electronic have children Phones
So in your Category.php
model u can make that
/**
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function parent() {
return $this->belongsTo(self::class, 'parent_id');
}
/**
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function children() {
return $this->hasMany(self::class, 'parent_id','id');
}
Now u can use foreach to display your children and category! Hope that helpful! ;)
Laravel multiple models relationship
You need to use the hasManyThrough relation.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Category extends Model {
/**
* Get all of the products for the project.
*/
public function products()
{
return $this->hasManyThrough(Product::class, Subcategory::class);
}
}
You can use this relation as
$category = App\Models\Category::Find(1);
$products = $category->products
How to get products of a main category if a product is related to only one subcategory?
One common solution to this problem of querying a hierarchical data structure is a Closure Table. There are many discussions of this pattern online, so I won't attempt to restate fully, but the short summary is that you store every path between each object and all of its ancestors along with the depth between them. This gives you a table with columns (ancestor_id, descendant_id, depth), so you can join through that table to collect all objects linked to any of a given descendant's ancestors, or any ancestor's descendants.
Here is an example query for how this works in practice to query all descendants of a given ancestor category, possibly with some syntax issues because I don't have a real database to run this against.
SELECT products.* FROM products
INNER JOIN category_closure ON products.category_id = category_closure.descendant_id
WHERE category_closure.ancestor_id = 1;
We currently use this solution for virtually the exact same problem, products assigned anywhere within a hierarchy of categories. However, we are doing this in a Doctrine project, so implementation details of our solution likely wouldn't help here.
There are existing libraries to make this easier in Laravel, such as https://github.com/franzose/ClosureTable (I can't vouch for quality, just found now in a search).
Laravel Eloquent - Get nested relationships with filtered data
you can repeat the same condition on eager loading:
$Categories = Categories::whereHas('subcategories', function ($q) use ($request) {
$q->whereHas('products', function ($q) use ($request) {
$q->where('name', 'LIKE', "%$request->search%")
->orWhere('article_number', 'LIKE', "%$request->search%");
});
})->with(['subcategories'=> function ($q) use ($request) {
$q->with(['products'=>function ($q) use ($request) {
$q->where('name', 'LIKE', "%$request->search%")
->orWhere('article_number', 'LIKE', "%$request->search%");
}]);
}])->get();
Laravel, many-to-many relationship among multiple models
The error "error like id ambiguous" means that you need to specify the table in your where('id', 1)
like where('table.id', 1)
so that MySQL knows which id
column in which table you mean.
You can constrain the models returned by with
like this:
Category::with(['subcats' => function(Builder $query) {
$query->where('id', '=', 1);
}]);
Also you can count relations:
$subcat = SubCategory::withCount(['approvednews']);
$subcat->approvednews_count;
Limiting eager loaded relations is not possible per the docs.
A workaround may be to go the other way round starting from ApprovedNews
:
ApprovedNews::whereHas(['subcategories' => function(Builder $query) {
$query->where('id', '=', 1);
}])->limit(10);
Related Topics
How to Generate Unique Random Value for Each User in Laravel and Add It to Database
Dynamic Menu and Role Permission in Codeigniter
How to Add Whatsapp Share Button to PHP Website
Count Same Values in Array and Combine into Array
Creating Advanced Search Query With PHP Mysqli
Easiest Way to Replace All Characters in Even Positions in a String.
Remove Comma on Last Item of Foreach
Mysql Combine Two Columns into One in Query
Laravel: Display Difference Between Two Dates in Blade
PHP - Ssl Certificate Error: Unable to Get Local Issuer Certificate
Option Selected With Codeigniter and Data from Db
Php Curl Required Only to Send and Not Wait for Response
Api to Get All the Reviews and Rating from Google for Business
I Have Three Columns, I Want to Combine Them All in One Main_Table
Success Message Pop-Up After from Submit Button Clicked
How to Store .Pdf Files into MySQL as Blobs Using PHP
Getting Data from a Textarea into a Database
Auto Update Cart on Quantity Change in Woocommerce Cart Page