How to query from multiple tables Laravel DB - laravel-5

Im new to laravel db query. I have problem when want to query.
I have two table customer and history. In history it have few column which are customer_id, activity (purchase,buyback), product_type(gold,silver) and quantity. Currently I want to retrieve balance for each of customer. To get balance, purchase - buyback.
-> customer_id | gold_balance | silver_balance
Here I attach two part of table and code to be review.
Thanks in advance.

You should create a hasMany relationship between Customer and History (maybe called histories) and create a custom attribute that loops through histories and add/subtract amount.
Something like this (not tested):
class Customer {
public function histories() {
return $this->hasMany(History::class);
}
public function getBalanceAttribute() {
return $this->histories->reduce(function($total, $current) {
$grossAmount = $current->amount * $current->quantity;
return $current->activity === 'purchase' ? $total - grossAmount : $total + grossAmount;
}, 0;
}
}

Related

Laravel: Load only pivot additional columns without relation

I have the following structure:
Charge
id
amount
created_at
..
Payment
id
amount
created_at
..
and a pivot table charge_payment, since one charge can be covered partially by multiple payments.
charge_payment
charge_id
payment_id
amount
The amount column on the pivot table defines the amount that the given Payment covers for the Charge.
And I need to get only the "paid" amount for a Payment.
I have the following models:
// Charge.php
class Charge extends Model
{
public function payments()
{
return $this->belongsToMany('App\Payment')->withPivot('amount');
}
}
// Payment.php
class Payment extends Model
{
public function charges()
{
return $this->belongsToMany('App\Charge')->withPivot('amount');
}
}
I want to be able to get only the paid amount with:
$payment = Payment::find(..);
$paid_amount = $payment->charges->sum('pivot.amount');
However, with this approach the related models are loaded from the database and I won't be needing them.
Is there a way to load only the additional pivot column without the related models?
Thank you very much!
Firstly, if one Payment can be always related only to one Charge, I would advise you to change the relationship from many-to-many to one-to-many (it will be just more correct and simpler).
Than you can simple use aggregate function (in your case withSum) which will return you only resulting values without relationship Models.
$payment = Payment::withSum('payments', 'amount')->find(..);
{{ $payment->payments_sum_amount }}

Laravel left join check if a conditon is greater than a count

I would like to check a limit in number of user payment where a limit is set on user table.
So i have the following database structure
table user
id,name,...,pay_limit
and payment table
table payment
id, user_id, payment_ref
So i have created the following code
$query = User::query();
//other stuff
$query->leftJoin('payment','payment.user_id','=','user.id')
//stuck
Am stuck on how to check if the totals of payments on a user is not greater than the user pay_limit
How can i check the above in a query
Simple with relations. Suppose payment model is Payment and payment amount in payment_amount column
class User extends Model{
public function payments()
{
return $this->hasMany(Payment::class);
}
public function getIsOverLimitedAttribute(): bool
{
//if you check amount
return $this->payments()->sum('payment_amount') > $this->pay_limit;
//or if you check count of payments
return $this->payments()->count() > $this->pay_limit;
}
public function scopeNoOverLimited($query){
return $query->withCount('payments')->having('payments_count', '<', $this->pay_limit);
}
}
And use
if($user->isOverLimited){
//do stuff
}
Or get not over limited users:
User::noOverLimited()->get();
In terms of performance (since you want to be able to return all such users), the best approach is to store a summary column in your users table... total_payment
You can update all current users maybe via a migration file as such:
$table->integer('total_payment')->unsigned()->nullable();
DB::update("update users set total_payment = ('select count(id) from payments where user_id = id')");
Then to get all such users, you can do:
User::whereRaw('total_payment > pay_limit')->get();
Then add a PaymentObserver to increase the total_payment on new successful payments.
If you don't have access to modify the table, you can still use a scope like, but this can be performance intensive if being run all the time such as on user login without caching:
public function scopeAboveLimit($query)
{
$id = $this->id;//user id
return $query->whereRaw("pay_limit < ('select count(id) from payments where user_id = $id')");
}

Laravel whereHas ManyToMany relation but then order by a value in the third table

I have 3 tables
entry (
id,
title,
other_stuff)
entry_award (
id,
award_id,
entry_id)
award (
id,
name,
type)
I am trying to create a laravel query which lets me get all the entries that have awards, and order them by award.type ASC
$Entries = Entry::with('award')
->whereHas('award', function ($query) {
$query->orderBy('award.award_id','ASC');
})->paginate(20);
But this doesn't work.
This is the sql version of it
SELECT DISTINCT entry.*
FROM entry, award, entry_award
WHERE entry.id = entry_award.entry_id
AND award.id = entry_award.award_id
ORDER BY award.type ASC;
Now I tried to just use the raw sql for it, but the problem seems to be that laravel does not then recognize the result as Entry models/objects. And i need to get other Entry relations later on in the html via blade.
So how can I either make a query-builder query that gets me all entries that have awards and orders them by award.type value
or use the raw sql but have Laravel see it as an array of Entry
objects instead of just an array of JSON values.
class Entry extends Model {
public function entry_award(){
return $this->belongsToMany('App\Award', 'entry_award');
}
}
class Award extends Model {
public function entries() {
return $this->belongsToMany('App\Entry', 'entry_award');
}
}

Laravel returns a Collection with duplicates of the first model

I'm developing a Laravel 5.7 (API) application with a PostgreSQL database behind it. The relevant Models are: User (customers and employees), Car, and Request.
An employee User creates a Request for a Car, that belongs to a customer User.
The relationships are:
Car (as customer) : User = n:m
Car : Request = 1:n
User : Request (as employee) = 1:n
(The data design is suboptimal, to put it mildly, but anyway, it's the given reality for now.)
Now to the actual issue. I want to display all Requests of a customer User:
Request::query()
->join('user_car', 'user_car.car_id', '=', 'request.car_id')
->join('user', 'user.id', '=', 'user_car.user_id')
->where('user.id', '=', $customer->id)
->select()
->get();
The customer with the given $customer->id has n Requests. And the length of the result Collection of the call above is correct. But all these n entries are duplicates of the first one. Means: I'm getting a list with n instances of Request#1.
Why does the first call return a list of references to the same Model object? Is it a (known) bug?
ADDITIONAL INFORMATION
Relationships:
class User extends \Illuminate\Foundation\Auth\User
{
// ...
public function cars()
{
return $this->belongsToMany('App\Car', 'user_car')->withTimestamps();
}
public function requests()
{
return $this->hasMany(Request::class, 'user_id');
}
}
class Car extends Model
{
// ...
public function users()
{
return $this->belongsToMany('App\User', 'user_car')->withTimestamps();
}
public function requests()
{
return $this->hasMany(Request::class);
}
}
class Request extends Model
{
// ...
public function car()
{
return $this->belongsTo(Car::class);
}
public function user()
{
return $this->belongsTo(User::class);
}
}
The query is correct.
I logged the database requests, got the generated statement
SELECT *
FROM "request"
INNER JOIN "user_car" ON "user_car"."car_id" = "request"."car_id"
INNER JOIN "user" ON "user"."id" = "user_car"."user_id"
WHERE "user"."id" = 1;
..., and executed it manually. The result table contains as expected n different entries.
NOT just references
The result Collection's entries instances references to the different objects:
$test1 = $resultCollection->first();
$test2 = $resultCollection->last();
$test3 = spl_object_hash($test1);
$test4 = spl_object_hash($test2);
Xdebug output:
$test3 = "0000000077505ccd000000007964e0a8" <-- ccd0
$test4 = "0000000077505c33000000007964e0a8" <-- c330
Workaround
I found a workaround. This call
Request::whereIn('car_id', $customer->cars()->pluck('id')->toArray())->get();
... retrieves the correct/expected set of model.
First, note that your object hashes are not actually identical, and you're likely dealing with two separate instances.
What you're likely experiencing is an issue with ambiguous column names. When you JOIN together multiple tables, any matching/duplicate column names will contain the value of the last matching column. Your SQL GUI/client usually separates these. Unfortunately Laravel doesn't have a prefixing mechanism, and just uses an associative array.
Assuming all of your tables have a primary key column of id, every Request object in your result set will likely have the same ID - the User's ID you pass in the WHERE condition.
You can fix this in your existing query by explicitly selecting the columns you need to prevent ambiguity. Use ->select(['request.*']) to limit the returned info to the Request object data.

Nested Many to Many Relationship in Laravel

I have the table structures as
products id
packs id
pack_products pack_id, product_id
pack_optional_products pack_id, product_id
So in the above table, pack will have 2 type of products, compulsory products and optional products, mean if customer buy the pack the products which are attached in that pack as compulsory will automatically ordered, but customer also can see if there is any optional product in the pack so customer can also buy that product too.
Now to manage orders I have the following table.
orders id, customer_id
order_pack order_id, pack_id
Here everything works fine, using attach method as $order->packs()->attach($pack["pack_id"]);
So here problem starts ( when I tried to add optional ordered products in the ordered pack), to manage optional products order, I have created the following table
order_pack_product order_id, pack_id, pack_optional_product_id
I have created a model as.
class Order extends Model
{
//
public function packs(){
return $this->belongsToMany(Pack::class)->withTimestamps()->withPivot('name');
}
public function parent() {
return $this->belongsTo(ParentCustomer::class);
}
}
class OrderPack extends Model
{
//
public function optionalProducts()
{
return $this->belongsToMany(PackOptionalProduct::class, 'order_pack_product')->withTimestamps();
}
}
And then I call the method as.
$order->packs()->optionalProducts()->attach($optionalProduct["pack_optional_product_id"]);
and I'm getting this error.
BadMethodCallException: Call to undefined method
Illuminate\Database\Eloquent\Relations\BelongsToMany::optionalProducts()
in file
/.../....../laravel/framework/src/Illuminate/Support/Traits/ForwardsCalls.php
on line 50
SO complete code related to above tables will be this.
$order = new Order();
$order->parent_id = $parent->id;
$order->school_id = $schoolId;
if($order->save()){
foreach($json["packs"] as $pack){
$order->packs()->attach($pack["pack_id"], ["child_name" => $pack["child_name"]]);
foreach($pack["optional_products"] as $optionalProduct){
$order->packs()->optionalProducts()->attach($optionalProduct["pack_optional_product_id"]);
}
}
return response()->json(["status" => "ok", "order_id" => $order->id]);
}else{
return response()->json(["status" => "failed"]);
}
optionalProducts() is method of model, not of relation packs().
Method $order->packs() - returns relation object, attribute $order->packs - returns collection of pack models.
You need to iterate trough collection, to attach optionalProducts to every one pack model.
foreach($pack["optional_products"] as $optionalProduct){
foreach($order->packs as $item){
$item->optionalProducts()->attach($optionalProduct["pack_optional_product_id"])
}
}
Perhaps, this code will not correct the error, then you need to correct your code logic.

Resources