How to update product quantity after 'approved' status? - laravel

I have these tables:
products:
id - name - quantity - etc
2 watch 4
4 T-shirt 2
orders:
id - user_id - address_id - etc
pivot table between them called order_product
order_id - product_id - quantity
1 2 3
1 4 1
The relation:
/**
* Products table relation
*/
public function products()
{
return $this->belongsToMany('App\Models\Product')->withPivot('quantity');
}
/**
* Orders table relation
*/
public function orders()
{
return $this->belongsToMany('App\Models\Order')->withPivot('quantity');
}
I need when I update the status to approved then update my quantity product!
My shut: ( Here I'm confused because the product can be many! the quantity as well )
public function status_orders(Order $order ,Request $request)
{
if($request->status == 'approved'){
$product_quantity = $order->products->pluck('quantity');
foreach($order->products as $order){
$order_quantity = $order->pivot->quantity;
}
$final_quantity = $product_quantity - $order_quantity;
}
}

you want to update product table quantity after an order is approved. right?? you can do it the following way
public function status_orders(Order $order ,Request $request) {
if($request->status == 'approved') {
foreach($order->products as $product) {
$product->update([
'quantity' => $product->quantity - $product->pivot->quantity
]);
}
}
}

Related

How to merge categories table with items table and returtn array of each category with items

I have three tables and after each table is the defined eloquent relationship of each entity.
categories
id
name
1
cars
2
bikes
public function items()
{
return $this->belongsToMany(AccountItem::class, "category_item", "category_id", "item_id");
}
category_items
id
category_id
item_id
1
1
1
2
1
2
items
id
name
1
volks
2
bmw
public function categories()
{
return $this->belongsToMany(Category::class, "category_items", "item_id", "category_id");
}
I am stuck on how to get a function that will return an array of the data with each category and the corresponding items. Incase the category has null items it returns a empty array of the category.
I assume your relationship is correct. If so, you can do this to load.
$categories = Category::with('items')->get();
foreach ($categories as $category) {
$categoryArray = [
'id' => $category->id,
'name' => $category->name,
'items' => $category->items->toArray()
];
}

sum of columns in another table - laravel

There's a loan table and loan_addition table. How can I sum the added_amt of loan_addition table and show them while returning loan table data?
loan_addition table
id loan_id added_amt
1 1 100
2 1 200
controller
$data = Loan::select('*')
->with('loanAddition') // how to sum all the columns of respective loan_id here
->get();
dd($data);
loan model
class Loan extends Model
{
public function loanAddition() {
return $this->hasMany(LoanAddition::class);
}
}
LoanAddition model
class LoanAddition extends Model
{
public function loan()
{ return $this->belongsTo(Loan::class); }
}
Thanks in advance..
You can use withSum() method as stated here
$records = Loan::select('*')->withSum('loanAddition', 'loan_id')->get();
Then get the data like below:
$records->pluck('loanAdditions_sum_loan_ids');
Update: for laravel below 8.12
Loan::select('*')->withCount(['loanAddition as loan_id'=>function($query){
$query->select(DB::raw("SUM(loan_id) as loan_id"));
}])->get()
$data = Loan::select('*')
->with(['loanAddition',function($query){
$query->select('sum(added_amt) as sum_added_amt')
}]) // how to sum all the columns of respective loan_id here
->get();
dd($data);
or you can do is $data->first()->sum('loanAddition.added_amt) where you want sum

how can I get the "value" field from the pivot table (product to "value")? -Laravel

i'm trying to create a simple relationship between tables :
- attribute_products -
id
name
- products -
id
name
price
pivot table to link them :
- attribute_product_value -
attribute_type_id
value
product_id
Products Model
public function attributeProduct(){
return $this->belongsToMany(AttributeProduct::class,'attribute_product_values','product_id','attribute_id');
}
attribute_products model
public function product()
{
return $this->belongsToMany(Product::Class,'attribute_product_values','attribute_id','product_id');
}
how can I get the "value" field from the pivot table (product to "value")?
As per Laravel documentation if the intermediate table has extra columns it needs to be specified while defining relationship
//Product
public function attributeProduct(){
return $this->belongsToMany(
AttributeProduct::class,
'attribute_product_values',
'product_id',
'attribute_id'
)
->withPivot('value');
//If you want created_at and updated_at on pivot table
///withTimestamps();
}
//AttributesProduct
public function product()
{
return $this->belongsToMany(
Product::Class,
'attribute_product_values',
'attribute_id',
'product_id'
)
->withPivot('value');
//If you want created_at and updated_at on pivot table
///withTimestamps();
}
To access the column in the intermediate table
$attributeProduct = AttributesProduct::find(1);
foreach($arrtibutesProduct->products as $prouct)
{
$product->pivot->value;
}
You can customise pivot attribute name
See https://laravel.com/docs/8.x/eloquent-relationships#retrieving-intermediate-table-columns

How to synchronise child table data on hasMany relationship?

I have 2 table products and variants, with a hasMany relationship, the structure is below :
Product Model :
public function variants()
{
return $this->hasMany(Variant::class);
}
Variant Model :
public function product()
{
return $this->belongsTo(Product::class);
}
Product Table :
| id name image manufacturer
| 1 T-Shirt t-s.jpg docomo
| 2 Short Skirt s-skirt.jpg docomo
Variant Table :
| id product_id name price sku quantity
| 1 1 S 30 ts-s 100
| 2 1 M 32 ts-m 100
| 3 1 XL 35 ts-xl 100
| 4 2 S 23 sk-s 100
| 5 2 M 25 sk-m 100
| 6 2 XL 28 sk-xl 100
I can save data on Variant model (child table) from Product model as :
public function store(Request $request)
{
$q = new Product;
$q->name = $request->name;
$q->save();
// Below child table
$q->variants()->createMany($request->variant);
}
I can store data, but the problem is that, how can I update child table? [It can be create, update or delete]
I tried with sync() method, but didn't work. Its for manyToMany relationship.
public function update(Request $request)
{
$q = Product::findOrFail($request->id);
$q->name = $request->name;
$q->save();
// Below child table update
// $q->variants()->sync($request->variant); // not worked
}
sync() works in manyToMany relationship. I need the same for hasMany relationship.
How can I do that?
Unfortunately there is no sync method for hasMany relations. It's pretty simple to do it by yourself. You can simple delete the rows and insert them all again.
public function update(Request $request, Product $product)
{
$product->update(['name' => $request->name]);
// Below child table update
$product->variants()->delete();
$product->variants()->sync($request->variant);
}

Eloquent relationship in custom pivot table

I might be overcomplicating things, but here's relationship I'm trying to write in Eloquent (Laravel 5):
I have a list of products and price lists. Each product can have many price lists. This is easy to do, but here's another thing - for every product <> price list assignment I can have many prices based on quantity, so it's like:
productID: 1010
priceListId: 1
min quantity: 1 -> price 10.00
min quantity: 5 -> price 9.50
min quantity: 10 -> price 9.00
productID: 1010
priceListId: 2
min quantity: 1 -> price 15.00
min quantity: 40 -> price 14.00
min quantity: 90 -> price 12.00
I think I know how to create custom pivot table although I don't know how to use it. I followed this link now I'm not sure if my code is correct and how to use it.
At the moment I have:
Product model:
class Product extends Model {
public function pricelists()
{
return $this->belongsToMany('PriceList');
}
public function newPivot(Model $parent, array $attributes, $table, $exists)
{
if ($parent instanceof PriceList)
{
return new ProductPricePivot($parent, $attributes, $table, $exists);
}
return parent::newPivot($parent, $attributes, $table, $exists);
}
}
PriceList model:
class PriceList extends Model {
public function products()
{
return $this->belongsToMany('Product');
}
public function newPivot(Model $parent, array $attributes, $table, $exists)
{
if ($parent instanceof Product)
{
return new ProductPricePivot($parent, $attributes, $table, $exists);
}
return parent::newPivot($parent, $attributes, $table, $exists);
}
}
Pivot:
class ProductPricePivot extends Pivot {
public function product()
{
return $this->belongsTo('Product');
}
public function pricelist()
{
return $this->belongsTo('PriceList');
}
public function prices()
{
return $this->hasMany('ProductPrice');
}
}
Now ProductPrice extends Model again and is just a standard model without any additional methods.
Is this correct? If so, then following example from above, how can I add new quantity/price level to price list 1 on product 1010?
At the moment, when creating relationships, I'm doing:
$productID = 1010;
$priceListID = 1;
$priceList = PriceList::find($priceListID);
$priceList->products()->attach($productID);
$productToPriceList = $priceList->products()->find($productID);
And I'm lost here... I find this relationship, but how can I now attach next quantity <> price level to it?
Can someone please give an example of how to use such relationship or links to pages where I can find something more about it? And yes, I check Laravel documentation, and yes, I googled it as well.
Thank you!
As you described the case, I see here two types of relationships:
Many-to-Many relationship between Product & PriceList
Many-to-One relationship between PriceList & ProductPrice (which holds the "min-quantity" and "price") values.
I'm assuming that you don't need the same price condition for many "price-list"s. Every list will have it's price conditions.
Many-to-one relationship doesn't require pivot table.
Follow this link, you'll find that laravel Eloquent system helps you much.
You need 4 tables: products, price_lists, product_prices, products_to_pricelists (the pivot)
the products_to_pricelists table look like that:
*====*============*===============*
| id | product_id | price_list_id |
*====*============*===============*
Now the models:
Products:
class Product extends Eloquent {
protected $table = 'products';
public function price_lists()
{
return $this->belongsToMany('PriceList', 'products_to_pricelists', 'price_list_id');
}
}
Price lists:
class PriceList extends Eloquent {
protected $table = 'price_lists';
public function prices()
{
return $this->hasMany('ProductPrice');
}
}
Prices:
class ProductPrice extends Eloquent {
protected $table = 'product_prices';
}
Now it's easy:
$productID = 1010;
$list_id = 1;
$theProduct = Product::find( $productID );
$theProductPriceLists = $theProduct->price_lists; // Don't use parens
$theList = Product::find( $productID )->price_lists()->where('price_lists.id', $list_id)->first(); // Here you use parens
$theListPrices = $theList->prices; // Again no parens
Laravel just manage for you the pivot-connection!
Hope that's help

Resources