Good day. Like I explained in this post Using Query Builder and MySql to get categories and sub - categories, I want to make something meaningful from this table. I decided to go the Eloquent way. I am able to get the distinct categories as shown below. How do i loop through each title belonging to a a particular category?
For example, get it in the form:
CatA
Title 1
Title 5
CatB
Title 2
Title 3
Title 4
My code is shown below
public function type(Request $request){
$details = [];
$categories = Category::distinct()->get(['category']); //Get the distinct categories from the category column in the table
foreach($categories as $category){
$titles = Category::where('type',$category->type);
$details = ['cat'=>$category->type,[
'title' => $titles->title,
'pk' => $titles->pk
]];
}
return response()->json([
"Data" => $details
]);
}
Not getting a result. Is there a better way this can be done please?
You can make many to many relationship with post and category. Then get all categories with posts.
Example:
$categories = Category::with('posts')->all();
Then you can loop through categories and posts
foreach($categories as $category){
foreach($category->posts as $post){
echo $post->title;
}
}
Documentation: https://laravel.com/docs/8.x/eloquent-relationships#many-to-many
Related
I'm developing a simple web shop where I have a category list that has a has many relationship with categories.
+topcategory
-subcategory 1
-subcategory 2
....
When I click on top category I want to receive all products from the subcategories as well.
How to achieve this in CakePHP 3?
I use this for finding the products at the moment:
$products = $this->paginate($this->Products->find('threaded')
->where([
'Categories.slug' => $slug
])
);
Additional associations can be loaded to the paginated table by using the contain parameter:
$this->paginate['contain'] = [
'Categories' => function (\Cake\ORM\Query $query) use ($slug) {
return $query->where(['Categories.slug' => $slug]);
}
];
$products = $this->paginate($this->Products);
See also
Joining Additional Associations
I'm trying to show products related to the category. In my menu I have a list of categories if I click this category i want to see related products to this category. I'm just learning laravel can somebody help me out..
DATABASE:
-categories: ID, NAME
-products: has Category_id
View
Route::get('/category' , [
'uses' => 'productController#getCategory',
'as' => 'category.single'
]);
Controller
public function getCategory($category) {
$singleCategory = Category::find($category);
return view('pages.category', ['category' => $singleCategory]);
}
How do I go from here?
in Category.php Model add a relation
public function products()
{
return $this->hasMany('App\Product');
}
then you can call
$singleCategory->products
and you'll get you products by category_id
As per the following lines:
$singleCategory = Category::find($category);
return view('pages.category', ['category' => $singleCategory]);
category list is available on pages.category page under $category. Its a Collection object, you can access its object by using foreach() loop.
How do I go from here?
I don't know.
But for your problem, if you want to get the products of a Category just do:
$singleCategory = Category::find($category);
$products = $singleCategory->products;
(I assume you added a products method in your Category model, if not, read this: https://laravel.com/docs/5.4/eloquent-relationships#one-to-many).
Then you can display your products by looping on your products:
foreach($products as $product) {
echo $product->name;
}
I have category (Category model).
Each category has child categories (via Category model field parent_id).
Each child category has products (via Product field category_id).
I need to get the latest added product for each parent category. And ideally it should take one request. Or as less requests as possible.
I think it should work via relation and looks something like the following:
$areas = Category::find()
->parent()
->published()
->orderBy('position ASC')
->with('latestProduct')
->limit(8)
->asArray()
->all();
public function getLatestProduct()
{
return $this->hasOne(Product::className(), ['category_id' => 'id'])
->viaTable('category', ['parent_id' => 'id'])
->published()
->with('firstImage')
->orderBy('date_create DESC');
}
This piece of code doesn't work as expected. Is it written correctly and how I should implement this type of task?
In your Category model, you can do something like this.
public function latestProducts()
{
return Product::find()->where(['category_id' => $this->id])->published()->with('firstImage')->orderBy('date_create DESC')->all();
}
In your view while looping for each category, call this function as shown below.
$category->latestProducts(); // where $category is the current category in loop
I have an Item object which has a 1:n relation to categories. My Item Model contains:
setCategories(\TYPO3\CMS\Extbase\Persistence\ObjectStorage $categories)
getCategories()
addCategory(VENDX\Items\Domain\Model\Category $category)
removeCategory(VENDX\Items\Domain\Model\Category $category)
but I am not able to add multiple categories to an itemobject.
i tried:
$category = $this->objectManager->get('VENDX\Items\Domain\Model\Category');
$category->setCatName('Cat1'); //First category
$item->addCatgeory($category);
$category->setCatName('Cat2'); //Second category
$item->addCategory($category);
after adding $item to my $itemrepository it just saves the last category "Cat2" into the db. What am i missing??
also tried that:
$categories = $this->objectManager->get('TYPO3\CMS\Extbase\Persistence\ObjectStorage');
$category = $this->objectManager->get('VENDX\Items\Domain\Model\Category');
$category->setCatName('Cat1'); //First category
$categories->attach($category);
$category->setCatName('Cat2'); //Second category
$categories->attach($category);
$item->setCategories($categories);
same issue with the above code. It just saves the last (second) category. How can i add multiple categories to my item-object?
Well i made a fatal error when using the SAME category-object. In fact i just changed its CatName value. In ORM we need one object for each "value". Means we can't use the same object for multiple "object-allocations" like i did above. So the correct way of achieving my purpose is:
$categories = $this->objectManager->get('TYPO3\CMS\Extbase\Persistence\ObjectStorage');
$category1 = $this->objectManager->get('VENDX\Items\Domain\Model\Category'); //1st catobj
$category1->setCatName('Cat1'); //First category
$categories->attach($category1);
$category2 = $this->objectManager->get('VENDX\Items\Domain\Model\Category'); //2nd catobj
$category2->setCatName('Cat2'); //Second category
$categories->attach($category2);
$item->setCategories($categories);
another "mistake" was using the objectManager for entities-instantiation. I was told to construct them via "new" instead of "overheading" the extension with the objectManager.
so my final solution is:
$categories = new \TYPO3\CMS\Extbase\Persistence\ObjectStorage;
$category1 = new \VENDX\Items\Domain\Model\Category; //1st catobj
$category1->setCatName('Cat1'); //First category
$categories->attach($category1);
$category2 = new \VENDX\Items\Domain\Model\Category; //2nd catobj
$category2->setCatName('Cat2'); //Second category
$categories->attach($category2);
$item->setCategories($categories);
I have 2 many to many relationship tables; Posts and Categories. One post can have many categories. My question is how can I show list of posts with their categories?
Like that:
My post 1 (cat1, cat2, cat3)
My post 2 (cat2, cat3)
My post 3 (cat1)
I've tried these methods;
// Create post object
$p = new Post();
// Get 30 posts
$p->get(30);
// Loop through all posts
foreach ($p as $post)
{
// Get the current user's group
$post->category->get();
foreach($post->category as $category) {
// ...
}
}
Don't like this, because if I'm get 30 posts, then on every post loop again make a query and find category again and again.
and tried this:
$p = new Post();
$p->include_related('category', array('id', 'name'), TRUE, TRUE)->get(30);
foreach($p as $post) {
// ...
foreach($post->category as $category) {
// ...
}
}
This is more close, but this one problem is I setting limit get(30) so if my per post have 2 categories than showing 15 post + 15 categories.
What is the true method for many to many listing?
Well in this case i will opt for caching both tables in php associative arrays, and then loop just the arrays.