laravel 5 many to many not working - laravel-5

I have a many to many relationship between Products and Categories Table with Pivot table as Product_Category
In Products Model:
public function categories(){
return $this->belongsToMany('\App\Models\Categories', 'product_category', 'product_id', 'category_id');
}
In Categories Model:
public function products(){
return $this->belongsToMany('\App\Models\Products', 'product_category', 'category_id', 'product_id');
}
In Product_Category Model:
public function products(){
return $this->belongsTo('App\Models\Products');
}
public function categories() {
return $this->belongsTo('App\Models\Categories');
}
In ProductController:
$data = Products::with('categories')->select('id','product_name','user_id','created_at')->orderBy('id', 'desc')->paginate(20);
Then i test with function below:
foreach ($data as $val) {
$cats = $val['categories'];
}
I try to var_dump(), but nothing happened:
object(Illuminate\Database\Eloquent\Collection)#472 (1) {
["items":protected]=> array(0) { }
}
Please help me

When you have created a Pivot Model in your application, then This pivot table has a one-to-many relationship with each of your corresponding models. i.e. Product_Category model has a one-to-many relationship with Products and Categories Models. So, code in Products and Categories Models will be like below:
In Products Model:
public function categories(){
return $this->hasMany('\App\Models\ProductCategory', 'category_id');
}
In Categories Model:
public function products(){
return $this->hasMany('\App\Models\ProductCategory','product_id');
}
Do the changes as above and it should be working.

Related

How to get product name from pivot table using laravel?

I am trying to get product name from pivot table but unfortunately i have no idea how can i get product name from pivot table please help me thanks.
Product Model
public function category()
{
return $this->belongsToMany('App\ProductCategory', 'product_category', 'product_id', 'mf_product_category_id');
}
productcategory model
public function products()
{
return $this->belongsToMany('App\Product', 'product_category', 'mf_product_category_id', 'product_id');
}
controller
public function getproduct(Request $request)
{
// getting category Id
$categoryId = $request->category;
// getting product Id
$name = trim($request->product);
$productId = Product::where('name', $name)->pluck('id');
$getProductcategory = ProductCategoryCount::whereIn('mf_product_category_id', $categoryId)->whereIn('product_id', $productId)->get();
return $getProductcategory;
// return response()->json($getproduct);
}
As stated in laravel doc, you can retrieve pivot table extra data using withPivot on the relationship.
Define category in the Product Model
public function category()
{
return $this->belongsToMany('App\ProductCategory', 'product_category', 'product_id', 'mf_product_category_id')
->withPivot('Your_extra_data_on_pivot_table');
}
And by querying products, you can get category (which I suggest to be categories). You can retrieve it like this $products->first()->pivot->{name of_your_extra_data_on_pivot_table}
It is more optimized if you eager load this relationship.

Reach the subcategory from the Product model (Laravel)

I am trying to reach the last laravel model from the first one with eloquent relationships. How can I reach the Subcategory directly from Product?
The 3 Models I have:
Product (id, category_id, etc..)
public function categories()
{
return $this->belongsTo('App\Category', 'category_id');
}
Category (id, name)
public function products()
{
return $this->hasMany('App\Product', 'category_id');
}
public function sub_categories()
{
return $this->hasMany('App\SubCategory', 'category_id');
}
SubCategory (id, category_id, name)
public function categories()
{
return $this->belongsTo('App\Category', 'category_id');
}
I would've assumed I could reach it with
Product::find(1)->categories->sub_categories;
Am I missing something obvious here?
read this docs
Product
class Product extends Model
{
public function SubCategory()
{
return $this->hasManyThrough('App\Category', 'App\SubCategory');
}
}
In Addition add the subCategories method on Product model and also a product is belongs to a category not categories
and also always try to use camel case for the methods (subCategories)
replace your code with this
Product:
public function category()
{
return $this->belongsTo('App\Category', 'category_id');
}
public function subCategories()
{
return $this->category()->subCategories;
}
Category:
public function products()
{
return $this->hasMany('App\Product', 'category_id');
}
public function subCategories()
{
return $this->hasMany('App\SubCategory', 'category_id');
}
SubCategory:
public function categories()
{
return $this->belongsTo('App\Category', 'category_id');
}
finally use this to get the subcategories
Product::find(1)->subCategories;
Product::find(1)->categories is an array. You will have to loop it to get the subcategory of each category. See below
$categories = Product::find(1)->categories;
foreach ($categories as $category {
//Get subcategories for each category
dump($category->sub_categories);
}

Laravel get all products from nested categories

I'm trying to get all products from the nested categories by using eloquent...
DB structure
product
id
name
categories
id
parent_id
name
product_categories
product_id
category_id
Models
Product Model
public function categories(){
return $this->belongsToMany(Category::class,'product_categories');
}
public function scopeGetCategoriesProducts($query,$category){
return $query->with('categories')
->whereHas('categories', function ($q) use ($category) {
$q->where('parent_id', $category)
->orWhere('categories.id', $category);
})->where('status',1);
}
Category Model
public function products(){
return $this->belongsToMany(Product::class,'product_categories');
}
public function parent()
{
return $this->belongsTo('App\Models\Category', 'parent_id');
}
public function children()
{
return $this->hasMany('App\Models\Category', 'parent_id');
}
public function childrenRecursive(){
return $this->children()->with('childrenRecursive');
}
I have three level category tree ... By the code that i have i can get products from two levels...
Can someone help with this ? I'm strongly believe that there is a way to solve this with eloquent. Something like this
public function scopeGetCategoriesProducts($query,$category){
return $query->with('categories')
->whereHas('categories', function ($q) use ($category) {
$q->with('parent')
->whereHas('parent', function ($que) use ($category) {
$que->where('id',$category);
})->where('parent_id', $category)
->orWhere('categories.id', $category);
})->where('status',1);
}
Thanks for your help... waiting for your suggestions

Laravel, make nested SQL query with inner join on Eloquent and Laravel's Models

I have followng database:
Simply speaking, Users have many shops, Shops have many products etc.
I need to make this query with the help of Eloquent ORM:
SELECT * FROM tmp.shops
INNER JOIN
(SELECT * FROM tmp.products
WHERE tmp.products.shop_id IN
(SELECT id FROM shops where user_id = 1)) as nested_query
ON tmp.shops.id = nested_query.shop_id;
I need to catch information about each product in user's shop and info about shop.
About my Models. This is relation with Shop in User model
/**
* #return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function shop()
{
return $this->hasMany('App\Shop');
}
And this is Relations in Shop model:
public function user()
{
return $this->belongsTo('App\User');
}
public function products()
{
return $this->hasMany('App\Product');
}
Finaly, Product model:
public function shop()
{
return $this->belongsTo('App\Shop');
}
Eager load your shop's relation(with('shop')) defined in your product's model as
$user_id=1;
$products = Product::with('shop')
->whereHas('shop.user', function ($query) use($user_id) {
$query->where('id', '=', $user_id);
})
->get();
Models
class Product extends Model {
public function shop() {
return $this->belongsTo('Shop', 'shop_id');
}
}
class Shop extends Model {
public function user() {
return $this->belongsTo('User', 'user_id');
}
public function products() {
return $this->hasMany('Product', 'shop_id');
}
}
Now when you iterate products you will get shop details object in each product object

load all the posts with the many tags - Laravel

I have a polymorphic relationship between post <=> taggables <=> category. Each post has many tags and each category has many tags. How can I load all posts with the tags of the category?
Post:
public function tags()
{
return $this->morphToMany('App\Tag', 'taggable');
}
public function categories()
{
return $this->belongsToMany('App\Category', 'categories_posts');
}
Category:
public function tags()
{
return $this->morphToMany('App\Tag', 'taggable');
}
public function posts()
{
return $this->belongsToMany('App\Post', 'categories_posts');
}
Tag:
public function posts()
{
return $this->morphedByMany('App\Post', 'taggable');
}
public function categories()
{
return $this->morphedByMany('App\Category', 'taggable');
}
posts can have may categories and many categories can have many posts. But i dont have a table for that.
First define the pivot table for many-to-many relationship between posts and categories table
then you can get categories of post's tags
$post = Post::with('tags.categories')->find('x');
foreach($post->tags as $tag){
foreach($tag->categories as $category){
$category->name;
}
}

Resources