Getting an ID from Pivot table Eloquent belongsToMany() - Laravel 5.2 - laravel

I have two items. Shops & Categories. In my Shop model I have declared this relation :
public function categories()
{
return $this->belongsToMany('App\Models\Category');
}
and in my Category model I have this :
public function shops()
{
return $this->belongsToMany('App\Models\Shop');
}
I am able to add Shop in to category by using attach. For example this code :
$shop->categories()->attach($cat_id);
By using the above attach method, a record is automatically created in my pivot table category_shop with category_id and shop_id.
Now, I have a shop loaded to $shop. Like below :
$shop = Shop::findOrFail($id);
Obviously now I have my shop id in $shop->id. My question is how can I get back the category id(s) of this shop by using the above setup.? I am new to laravel.

Since, shop has many categories. You will get many categories id.
$shop= Shop::findOrFail($id);
foreach($shop->categories as $category)
{
print_r($category->id);
}

Related

Laravel, many-to-many relationship among multiple models

I Have multiple models that have many to many relationship
Here are the models
News Section
Categories
Sub Categories
Approved News
Pending News
Each News Section can have multiple Categories.
Each Category can have multiple Sub Categories.
Each Sub Category can has multiple Approved News and Pending News.
I want to have News with Categories, Sub Categories and Pending / Approve news
and stuff like
Categories with Sub Categories and Approve news
I tried with pivot tables but not able to get results
Models are as follow
News Section
class NewsSection extends Model
{
public function categories()
{
return $this->belongsToMany(Category::class);
}
}
Category
class Category extends Model
{
public function subcats(){
return $this->belongsToMany(SubCategory::class);
}
public function newssections(){
return $this->belongsToMany(NewsSection::class);
}
}
SubCategory
class SubCategory extends Model
{
public function category(){
return $this->belongsTo(Category::class);
}
public function approvednews(){
return $this->belongsToMany(ApprovedNews::class);
}
public function pendingnews(){
return $this->belongsToMany(PendingNews::class);
}
}
ApprovedNews
class ApprovedNews extends Model
{
public function subcategories (){
return $this->belongsToMany(SubCategory::class);
}
}
PendingdNews
class PendingdNewsextends Model
{
public function subcategories (){
return $this->belongsToMany(SubCategory::class);
}
}
Update
This what I have done so far
$news =Category::with('subcats.approvednews')->where('id',1)->get();
I got all the approved news with subcategories and categories
how can i modify this to get specific subcats and approved news per category, if i do this
$news =Category::with('subcats.approvednews')->where('subcats.id',1)->get();
I get an error like id ambiguous
Is it possible to pick and chose items from relation for instance return just 2 subcats and 3 approved news for each subcat of selected category
or
get count of approved news and pending news per subcat and category
Thanks in advance
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);
I have a few suggestions of how you can get this to work. In your comments, you say you are getting an issue doing the following:
$items=Category::with('subcategory')->where('id',1)->get();
Where is 'subcategory' coming from? By the looks of your model, your relationship between Category and Subcategory is called subcats. So you would need to change it to:
$items=Category::with('subcats')->where('id',1)->get();
And if you dump that out, you should see that you will get the category where the ID is 1, and the subcategories loaded in. A way to test that your relationships are working would be something like this:
$category = Category::find(1);
$subCats = $category->subcats()->get();
dd($subCats);
In your relationships, instead of using SubCategory::class I would suggest trying return $this->belongsToMany('App\SubCategory'); so that the models are definitely connected.
Once you have tested that your relationships between one another work, you can get started on testing that you can go from a->b->c etc.
May be using "Nested Eager Loading" and "scope", you can do something like
$pendings = NewSection::with('categories.subCategories')->pending()->get()
$approved = NewSection::with('categories.subCategories')->approved()->get()
not tested it, but you can try, may be with some modification, you can reach to your goal.
if you want return one collection, you may like to merge it
$approved->merge($pendings);
but, you should avoid it.

laravel has many through piviot table

I have 3 tables
Products
id, name, image
Offers
id,name
Offer_product
id,offer_id,product_id
I am accessing data of product table with pagination using
$list = Product::query()->paginate(6);
now i want the complete record of products with offer name stored in offers table . id of both product and offers are stored in offer_product table where one products can have many offers
In your DB design you have a Many-to-Many relation, which in Laravel is handle by belongsToMany https://laravel.com/docs/5.7/eloquent-relationships#many-to-many.
hasManyThrough is for cascade 1-to-Many -> 1-to-Many case. Let's say an Artist has many Albums and each Album has many Songs, then an Artist has many Songs through Albums. If you need an Artist Songs, then you may use directly hasManyThrough.
In your case your relation in Product.php model should be :
public function offers() {
return $this->belongsToMany(Offer::class, 'Offer_product')->withPivot('id');
}
In Offer.php model :
public function products() {
return $this->belongsToMany(Product::class, 'Offer_product')->withPivot('id');
}
Now if you want all of them with eager loading https://laravel.com/docs/5.7/eloquent-relationships#eager-loading to avoid N(products)+1 calls to database :
$products = Product::with('offers')->get();
foreach ($products as $product) {
echo 'product : '.$product->name.'<br/>';
foreach($product->offers as $offer) {
echo '<br>---- offer : '.$offer->name;
// once you called the relation, then you can access data on pivot table
echo ' - pivot id :'.$offer->pivot->id;
}
}

Laravel Fetching one to Many Relationship

Hello I am learning laravel and I am having an issue retrieving data from my relations.
In my database there are Product and Groups filled with dummy data.
I defined my relationship like this in product model:
public function Group()
{
return $this->hasMany('App\Groups','product_id', 'id');
}
And in my group vice versa with :
public function Product()
{
return $this->belongsTo('App\Product','product_id', 'id');
}
The way I am referencing to my products table is :
$table->foreign('product_id')->references('id')->on('products')->onDelete('cascade');
Now I have column product_id in my database under groups, and it is linked to if from products id it seems.
The groups table contains of its auto incremented id and product_id foreign key column.
While products table has auto incremented id and name column.
The issue is here :
How do I return the products that are not null or have value (of products id) in groups table.
I tried something like this in my filter controller:
public function getProductsWithGroup()
{
$Products = Product::with('groups')->get();
return $Products ;
}
But that is giving me call to undefined relations.
I am not sure how to access belongsTo or hasMany methods and whether I need an extra group_id column in my products table.
You named the relationship wrong. It should be groups & define in lowercase as
public function groups()
{
return $this->hasMany('App\Groups','product_id', 'id');
}
And use ->has() to check existence
public function getProductsWithGroup()
{
$Products = Product::has('groups')->get();
return $Products ;
}
->with() is used to eager load and ->has() is used to check existence & filter.
To get the products don't have any groups,
$Products = Product::doesntHave('groups')->get();
To see other ways to use ->has() check, https://laravel.com/docs/5.7/eloquent-relationships#querying-relationship-existence

How to connect three tables in Laravel?

I have thee tables: Orders, Products, Products_images.
I need to get ll orders, for this I do:
$orders = Order::with("products")->where("user_id", Auth::guard('api')->user()->id)->orderBy('id')->get();
Where with("products") is function in model Order
public function products()
{
return $this->hasOne("App\Product", "id", "product_id");
}
So, I have connected two table. Also I need connect with table Products with table Products_images in this query.
How can I do this?
Add a product_images function to the Products Model
public function product_images() { return $this->hasMany("App\ProductImage");}
Modify the above line's App\ProductImage to reflect the model for your table. Then you can access all the product images records that belongs to your products by doing the following:
$orders = Order::with("products.product_images")->where("user_id", Auth::guard('api')->user()->id)->orderBy('id')->get();
Look under nested eager loading on this link : https://laravel.com/docs/5.3/eloquent-relationships#eager-loading

Laravel Get products from multiple taxonomies

I have 3 tables, products, taxonomies and product_taxonomy. The 3rd table is a pivot table that contains product_id and taxonomy_id, meaning that product and taxonomy are many to many relationship. Given a list of taxonomy ids, how can I get all the products that belong to these taxonomies? NOTE: I want to have the products result set being able to paginated or order by maybe it's price or something.
You need to create many-to-many relationship and that requires relationship methods like:
// Product Model
public function taxonomies()
{
return $this->belongsToMany('Taxonomy');
}
// Taxonomy Model
public function products()
{
return $this->belongsToMany('Product');
}
The query:
$listOfTaxonomyIds = [1,2,3];
$products = Product::whereHas('taxonomies', function($query) use ($listOfTaxonomyIds){
$query->whereIn('taxonomy_id', $listOfTaxonomyIds);
})->get();

Resources