Reputation: 897
I want to pass in array of ids
and get all the category
of that ids
with all the banners of that category
I have defined relationship in ProductMainCategory.php
Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class ProductMainCategory extends Model
{
protected $hidden = ['created_at','updated_at'];
public function banners()
{
return $this->hasMany('App\ProductCategoryBanner', 'category_id');
}
}
The ProductCategoryBanner.php
Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class ProductCategoryBanner extends Model
{
protected $hidden = ['created_at','updated_at'];
}
And in My controller
//get distinct main_categories by id
$main_category_ids = Product::whereIn('id', $product_ids)
->select('main_category_id')
->distinct()
->pluck('main_category_id')
->toArray();
//get main_category with banners (error query)
$main_categories_with_images = ProductMainCategory::whereIn('id', $main_category_ids)
->with(array('banners'=>function($query){
$query->select('id','image');
}))
->get();
//this query works, but it'll give all the categories but i want only passed id's categories
$main_categories_with_images = ProductMainCategory::with('banners')
->get();
I'm getting the data but banners are empty
[
{
"id": 1,
"name": "Grocery & Staples",
"admin_id": 1,
"banners": [] //getting empty array
},
{
"id": 2,
"name": "Fruits & Vegetables",
"admin_id": 1,
"banners": [] //getting empty array
}
]
//actual result without $query->select('id','image'); is
[
{
"id": 1,
"name": "Grocery & Staples",
"admin_id": 1,
"banners": [
{
"id": 1,
"category_id": "1",
"image": "link 1",
"admin_id": 2
},
{
"id": 2,
"category_id": "1",
"image": "link 2",
"admin_id": 1
}
]
},
{
"id": 2,
"name": "Fruits & Vegetables",
"admin_id": 1,
"banners": [
{
"id": 3,
"category_id": "2",
"image": "link 3",
"admin_id": 1
},
{
"id": 4,
"category_id": "2",
"image": "link 4",
"admin_id": 1
}
]
}
]
Upvotes: 0
Views: 2122
Reputation: 15941
$main_categories_with_images = ProductMainCategory::whereIn('id', $main_category_ids)
->with(array('banners'=>function($query){
$query->select('id','image');
}))
->get();
Change WareIn
to WhereIn
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class ProductCategoryBanner extends Model
{
protected $hidden = ['created_at','updated_at'];
public function mainCategory() { return $this->belongsTo('ProductMainCategory')->select(['id','image']); }
}
Upvotes: 1
Reputation: 1405
change this :
//get main_category with banners (error query)
$main_categories_with_images = ProductMainCategory::whereIn('id', $main_category_ids)
->with(array('banners'=>function($query){
$query->select('id','image');
}))
->get();
Upvotes: 1
Reputation: 9369
You have typo after ProductMainCategory
: wareIn()
, It should be whereIn()
Upvotes: 0