Laravel eloquent relationship one to many - laravel

I am working on three tables: product, delivery and stock. I want that when a product is delivered, its quantity in the stock table increases. So in the controller of the delivery table I wrote this code:
$produit = Produit::find($delivery['produit_id']);
$quantite = $produit->stock->quantite;
$quantite += $delivery['quantite'];
$quantite->save();
but when I make a delivery, the quantity in the stock table does not change.

Simply types in PHP is not by reference, so you have to assign the new value to the Stock object. This is assuming quantite is an integer on the Stock model, which is not totally clear in the code you provided, since you call ->save() on quantite. Remember to save the Stock model instead of quantite.
$stock = $produit->stock;
$stock->quantite = $stock->quantite + $delivery['quantite']
$stock->save();

Related

How to add filter on item collection to get the Sales rep(total Quantity and Total no of Orders) of those Sale Managers which are logged in

$collection = $this->_itemCollectionFactory->create()->getCollection();
$collection->getSelect()->columns(array('total_orders' => new \Zend_Db_Expr('COUNT(order_id)')))
->columns(array('total_qty' => new \Zend_Db_Expr('ROUND(SUM(qty_ordered))')))
->group('sku');
$collection->getSelect()->limit(3);
$collection->addFieldToFilter('store_id', 2);
Through this code i can get the total quantity and total number of orders of all sales rep. But i need only those total quantity and total orders which were done by the Sales Rep og Logged in Sale Manager.
As you mentioned in your question you only want to get the order info based on a certain sales rep. To do that you need to somehow find a unique identify for the currently logged in sales rep and add a filter for that .
For example:
$collection = $this->_itemCollectionFactory->create()->getCollection();
$collection->getSelect()->columns(array('total_orders' => new \Zend_Db_Expr('COUNT(order_id)')))
->columns(array('total_qty' => new \Zend_Db_Expr('ROUND(SUM(qty_ordered))')))
->group('sku');
$collection->getSelect()->limit(3);
$collection->addFieldToFilter('store_id', 2);
$collection->addFieldToFilter('sales_rep_identifier', $loggedInSalesRepIdentifier);
The label sales_rep_identifier and the value $loggedInSalesRepIdentifier are just examples, you may have to adjust the format in which the data is stored if it doesn't currently have a field to check natively what sales rep did it, and adjust the values there accordingly
If you're using some kind of prebuilt system then maybe there are other labels for the identifier you could use, without more information on the specific database structure it's impossible to answer exactly, but essentially you need to filter by the unique sales rep identifier, and if that doesn't exist now in the database it should somehow but added

How to define the following relationship

I am developing a p2p app with laravel. I have two tables namely users and loans.
Firstly, a user can be a lender or borrower.
Then users can have multiple loans and multiple loans belong to multiple users.
Also, a loan can belong to one borrower and also to multiple lenders.
To explain it further, the loan record will be created by the borrower(or the user). Then the system will distribute the loan and assign it to multiple lenders.
Example: Let's say, one borrower wants a loan of 3000. Our system will distribute the loan as 2000 and 1000 (or 1500 and 1500, or 2500 and 500, etc.). Then assign it to two lenders.
Now it could be more lenders or bigger amounts.
So how can I define something like this with laravel eloquent?
Here's what I thought of till now.
Users and loans will have a many-to-many relationship.
Loans table will have a lender_data column which will be an array that contains lender_id and amount.
But I can't really figure out a way to fetch all the loans of a single lender. So how can I do that?
That's a lot of words. Thank you for reading.
First of all, this question is quite vague and doesn't show any code which I think all questions should. Its harder to answer questions like this that don't necessarily have predefined answers.
Personally, I'd look into intermediate table models:
https://laravel.com/docs/8.x/eloquent-relationships#defining-custom-intermediate-table-models
That way you can have a Lenders table, a Loan table, a Users table, and this "in between" table that could be something like a LoanAmount table. The LoanAmount table is mostly a pivot table (allowing the many to many relationship between Lenders and Loans), however it can also store data like:
loan_id lender_id amount
1 1 1000
1 2 1000
Then the loan table would just be
user_id amount
1 2000
So a User can have many Loans, but it's the Loans that can have many LoanAmounts.
I'd go with next:
class User extends Model
{
public function loans()
{
return $this->belongsToMany(Loan::class)->using(LoanUser::class)->withPivot(['amount', 'percentage']);
}
}
class Loan extends Model
{
public function users()
{
return $this->belongsToMany(User::class)->using(LoanUser::class)->withPivot(['amount', 'percentage']);
}
}
class LoanUser extends Pivot
{
protected $with = [
'landers',
];
public function landers()
{
return $this->belongsToMany(Lander::class)->withPivot(['percentage']);
}
}
class Lander extends Model
{
public function loanUsers()
{
return $this->belongsToMany(LoanUser::class)->withPivot(['percentage']);
}
}
In loan_user pivot table you should make field called percentage that will go to user from full amount. In second pivot between LoanUser and Lander lander_loan_user you should also need percentage field that you would assign to each lander_loan_user relation. It would be second pivot table data.
After you save loan_user data, you would need to attach landers to first pivot model (second pivot table doesn't require pivot model per description). Since there are eager loaded landers to pivot model, when you query some user and their loan
$user = User::where(['loan.amount' => 3000])->first();
$user->pivot->landers;// will get you related landers
You already have full amount in first pivot table and with percentage from same table you know how much user (borrower) gets and in pivot's relation to landers table you will know how much each lander gets from that loan.
It is like "T" relation where upper ends of 't' letter are Loan and User, that crossroad is LoanUser pivot and lower end (base) of the letter 't' are landers.
To avoid hard time as much as possible, keep up with eloquent's convention (check good practice here) and for example, instead of borrower_id call that loan_id, also pivot table to be loan_user (pay attention on pivot singular).
This was written from top of head and not tested but this is the idea/way how task can/should be finished.

Laravel Eloquent - Sum of a column values for multiple records from related data

I have the following models: User, Order, OrderPayment
whereby each user has many orders, and each order has many order payments.
The orderPayment model has the attribute "total_paid"
I would like to get the sum of the user's total paid for all his orders.
eg:
user has 3 orders.
the first order has the two following payment records: 5$ and 4$.
the second order has one payment of 10$
the third order has two payment records of 1$ and 4$
the total sum i want is 5 + 4+ 10+ 1+ 4 = 24$.
I have tried the following but it's not working at all :
$user->orders->orderpayment->sum('total_paid');
but i get this error
Property [orderPayment] does not exist on this collection instance
Since you want to sum values from the OrderPayment model, it is easier to start there. Try to write it like this:
OrderPayment::whereHas('order.user', function($query) use ($userId) {
$query->whereId($userId);
})->sum('total_paid');
Make sure all the relations are defined well.
Try:
$user->orders->orderpayment()->sum('total_paid');

Server Action: Loop through each record of model

I have a server action to update product costs when selected in tree view:
bom_obj = env["mrp.bom"]
for product in object.browse(context.get('active_ids')):
price = 0
bom = bom_obj._bom_find(product=product)
if bom:
price = product._calc_price(bom)
product.write({'standard_price':price})
But This unfortunately only selects records visible in tree view, not ALL the records in product.product
I tried:
bom_obj = env["mrp.bom"]
product_obj = env["product.product"]
product_ids = product_obj.search(cr, uid, [])
for product in product_ids:
price = 0
bom = bom_obj._bom_find(product=product)
if bom:
price = product._calc_price(bom)
product.write({'standard_price':price})
Could you please tell me how to loop through each record of product.product.
OR
instead, tell me how I would go about update price of record selected in m2o field.
I know how to trigger the code in server action, I just need to know how to get record from m2o field. I will use this when product_id is changed in Sale Order Line, to update the price as it is selected.
Thanks

How to get Product id using Super attribute in Magento?

I am working on ajax module for Shopping cart in Magento. Consider i have a configurable product with 2 simple products configured as its two sizes (Small an Medium). When user selects and adds the item to cart, i cannot see the specific product id (small) in the url.
But instead supper_attribute is posted to my controller.
Is it possible for me to get the actual product id of size "Small" with the super attribute.
Below is my supper attribute array
[super_attribute] => Array
(
[129] => 128
)
129 = attribute_id (Size)
128 = attribute value (Small)
Please suggest me in this scenario. Please let me know if my question is not clear.
Thanks
Try this:
$childProduct = Mage::getModel('catalog/product_type_configurable')->getProductByAttributes($request->getData('super_attribute'), $product);
Where $product is the configurable product object.
For the Class Reference

Resources