laravel has many through piviot table - laravel

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;
}
}

Related

How to get data from third table in eloquent relationships eloquent many to many relationship

I am using Eloquent ORM and I have Book model which connect to BookCategory model and BookCategory connect to Category. The l'm problem facing is how to include data from third table in eloquent relationships?
Book
id
name
Category
id
name
type
BookCategory
id
book_id
category_id
Lets say for example you want to get all the books of a certain category:
assuming your pivot table name is Book_Category
in your Category model:
public function books()
{
return $this->belongsToMany('App\Models\Book', 'Book_Category', 'category_id', 'book_id');
}
and you can eager load category books like :
$categories = Category::get()->load('books');
//OR
$categories = Category::with('books')->get();
If I understand you right, you are looking for the pivot attribute. This makes additional columns of the intermediate table available.
https://laravel.com/docs/8.x/eloquent-relationships#retrieving-intermediate-table-columns

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

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);
}

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

How to compact two relationship in one relationship

I have some issue when I wanna compact two relationships in Laravel.
There were 3 tables with model.
table1: episodes --> model: Episode
relations -- hasMany --> posts
-- belongsToMany --> users
pivot-table2: posts --> model: Post
columns -- episode_id
-- user_id
relations -- belongsTo --> user
-- belongsTo --> episode
table3: users --> model: User
Yes, It was a many-to-many relationship. We could get posts or users relationships on Episode model.
If I have a single model collection
$episode = new App\Episode
How could it eager load like
$episodes = new App\Episode::with('posts.user').
Maybe I could do like below
$episode = new App\Episode::with('posts.user')->where('id','=','targetId')
But It seems like would first join three tables then make a query to get target episode.
Is there any way works like
$episode = new App\Episode::find(targetId)-> with('posts.user')
If you are using posts table just as pivot table, you are doing it wrong.
Episode Model:
public function users()
{
return $this->belongsToMany('App\User', 'posts');
}
// I would name my pivot table different than posts, if you don't pass the second parameter Laravel will look for episode_user table
User Model:
public function episodes()
{
return $this->belongsToMany('App\Episode', 'posts');
}
In your controller:
$user = User::find(1);
$user->episodes();
$episodes = Episode::find(1);
$episodes->users();

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