Get data from pivot table - php

I have two tables with a pivot table
Table user
id | name | email
Table drinks
id | name | price
Pivot Table user_drinks
id | user_id | drink_id | quantity | price | status
Drink Model
public function users()
{
return $this->belongsToMany('App\User', 'user_drinks', 'drink_id', 'user_id')->withPivot('price', 'quantity')->withTimestamps();
}
User Model
public function drinks()
{
return $this->belongsToMany('App\Drink', 'user_drinks', 'drink_id', 'user_id')->withPivot('price', 'quantity')->withTimestamps();
}
I want to get the latest users that have bought drinks and the price and quantity from pivot table e.g
User 1 with name John has bought 2 cups of coffee at $50 dollars
User 2 with name Jane has bought 3 cups of coffee at $75 dollars

use this relation to the User model
public function drinks()
{
return $this->belongsToMany(Drink::class, 'user_drinks')->withPivot(['quantity', 'price','status'])->withTimestamps();
}
to get it:
$user = User::with(['drinks' => function ($q) {
$q->orderBy('created_at', 'desc');
}])->orderByDesc('drinks.created_at')->get();

Related

Laravel Multiple Relationship for a sum column

I have Three Models name Invoices, Invoiceitems and Products.
Each Invoices HasMany Relationship with Invoiceitems Model.
Each Invoiceitems HasOne Relationship with Products Model.
I need to sum of Invoiceitem product amount where the Product has category 4.
Table Structure
Invoice
id | date | total_amt
Invoiceitem
id | invoiceid | product_id | product_amt | quantity | total_amt
Product
id | product_name | category_id
Relationship
Invoice Model
public function invoiceitems()
{
return $this->hasMany('App\Invoiceitems', 'invoiceid', 'id');
}
Invoiceitem Model
public function products()
{
return $this->hasOne('App\Products', 'id', 'product_id');
}
Expected Report
Invoice No | Date | Veg Category Product Amt | NonVeg Category Product Amt | Total Amt
KL0001 | 15-05-2021 | 0.00 | 190.366 | 190.366
KL0002 | 16-05-2021 | 20.00 | 350.000 | 370.000
Currently we use following Helper Function to get Particular category Products Total Amount
function getInvdiscsumamt($inv_id, $prdtype)
{
$totaldisamt = Invoiceitems::Where('invoice_id', $inv_id)->whereHas('products', function ($query) use ($prdtype) {
$query->where('category_id', $prdtype);
})->sum('total_amt');
return $totalpdtamt;
}
How to display particular category products total amount using Elequoent method
You can try one of the aggregate functions that already exist in Eloquent, see https://laravel.com/docs/8.x/eloquent-relationships#other-aggregate-functions, for instance withSum:
$invoiceItem = InvoiceItem::query()
->where('invoice_id', $invId)
->withSum(['products', function($query) use ($productType) {
$query->where('category_id', $productType);
}, 'frequency'])
->first();
Your property will then be available using the property {relation}_{function}_{column}, so in this case products_sum_frequency.
Note that the withSum does not share anything with the with (or whereHas) function, that means that if you use a subselection in your query like ->with(['products', function($query){...}]) that will be a separate selection from the withSum query.
I also recommend to use proper camelcasing in your functions and also your models. I'd also use singular names for all your model class names. So Invoiceitems would become InvoiceItem (models/InvoiceItem.php). This is the default way to define it in laravel as far as I'm aware.

How I get users which are created by Auth::user

I have two table users and customer_details. I want to get users which are created by Auth::user(). The created_by column is in customer_details table.
User Table
| id | name | email | status |
|-----------------------------------------------|
| 1 | Admin | admin#email.com | Active |
| 2 | Customer | user#email.com | Active |
CustomerDetails Table
| id | user_id | added_by | address |
|-------------------------------------------|
| 1 | 2 | 1 | NY City |
This is my query
$customers = User::role('Customer')->whereIn('status', ['Active'])->get();
Want to get records where added_by is current auth user
$customers = User::role('Customer')->whereIn('added_by', Auth::id())->get();
I think this should help
here we are using Auth::id() to get the id of the current user and then using eloquent to search for it.
I am considering that here added_by column contains the ID;
Create a relation in your CustomerDetail model:
public function addedBy()
{
return $this->belongsTo(User::class, 'added_by');
}
Then, you can query using this relation:
CustomerDetail::whereHas('addedBy', function($query) {
return $query->where('id', auth()->id());
})->get();
This query returns all customer created by the user current logged in.
To get all users with it's customers created by the current logged in user, add a new relation, now to the user model:
public function customerDetail()
{
return $this->hasOne(CustomerDetail::class, 'added_by');
}
and query users with customers created byt the logged in user:
User::role('Customer')->whereHas('customerDetail', function($query) {
return $query->where('added_by', auth()->id());
})
->whereIn('status', ['Active'])
->get();

Attaching extra model to BelongstoMany relations

I have two tables (users and drinks) with a pivot table, the user has a hasOne relation with profiles table, is there a way to attach the profile table to the pivot table and get all data.
Table user
id | name | email
Table profile
id | user_id | picture
Table drinks
id | name | price
Pivot Table user_drinks
id | user_id | drink_id | quantity | price | status
Drink Model
public function users()
{
return $this->belongsToMany('App\User', 'user_drinks', 'drink_id', 'user_id')->withPivot('price', 'quantity')->withTimestamps();
}
User Model
public function drinks()
{
return $this->belongsToMany('App\Drink', 'user_drinks', 'drink_id', 'user_id')->withPivot('price', 'quantity')->withTimestamps();
}
public function profile() {
return $this->hasOne('App\Profile');
}
PS: I don't wanna write this with raw sql query, it's driving me nuts.
I wouldn't change the tables relation.
I'd use the ->with() function to get the profile information within the existing relations.
So $user->drinks()->where('drink_id', $drink_id)->with('profile')->get(); would be my guess.

Laravel user model with multiple one to one relationship

I want to set the User model to have a one-to-one relationship with the Student model as well as the Lecture model also.
I'm login in using the user table and from then it will map to the student or lecture table depending on the user type.
The problem is when I run app\user::find('a123')->lecture it will return the b345(Mr Steven) data.
And when I run app\user::find('b345')->student, it returns the a123(david) data.
Both result should have produce NULL because it doesnt matches the id.
New in Laravel thanks.
User table
id | password | type
a123 | 1234 | student
b345 | 1234 | lecture
Lecture table
lecture_id | id | name
b345 | b345 | Mr Steve
Student table
student_id | id | name
a123 | a123 | david
User model
public function student(){
return $this->hasOne(student::class,'student_id');
}
public function lecture(){
return $this->hasOne(lecture::class,'lecture_id');
}
Lecture model
protected $primaryKey = 'lecture_id';
public function User()
{
return $this->belongsTo(User::class,'id');
}
Student model
protected $primaryKey = 'student_id';
public function User()
{
return $this->belongsTo(User::class,'id');
}

Querying Many to Many polymorphic relationship in laravel

I've following tables:
contacts(id, name, email, phone_no),
events(id, title, start_date, end_date),
addresses(id, city, state, country, zip_code),
addressables(id, address_id, addressable_id, addressable_type)
Here addressables have many to many polymorphic relation for contacts events. addressables could also hold other polymorphic model class.
Addres Model
public function addressable()
{
return $this->morphTo();
}
Event/Contact Model
public function addresses()
{
return $this->morphToMany(Address::class, 'addressable');
}
I wanted to fetch addresses along with their associated models. I would appreciate if anyone could help me to
List addresses with associated models
List addresses for specific model type
List addresses group by model type
UPDATED
Expected Outcomes:
addresses
id | address
1 | New York, USA
2 | California, USA
3 | Nevada, USA
contacts
id | name
1 | Albert King
2 | Michelle Johnson
3 | Sujit Baniya
events
id | title
1 | Event 1
2 | Event 2
3 | Event 3
addressables
id | address_id | addressable_id | addressable_type
1 | 1 | 1 | Contact
2 | 2 | 1 | Event
3 | 3 | 2 | Contact
EXCEPTED RESULT for Address::with('addressables')
Address - ID 1
----Details (New York, USA)
----Contact (Albert King)
Address - ID 2
----Details (California, USA)
----Event (Event 1)
Address - ID 3
----Details (Nevada, USA)
----Contact (Michelle Johnson)
Thank you in advance!
According to Laravel's Documentation for many to many polymorphic relations,
you have to edit your address model and add methods for events and contacts like so:
//Get all the contacts that are assigned this address
public function contacts()
{
return $this->morphedByMany('App\Contact', 'addressable');
}
//Get all the events that are assigned this address
public function events()
{
return $this->morphedByMany('App\Event', 'addressable');
}
To answer your question
Then to get all addresses for a contact, you can use the addresses dynamic property like so:
$contact = App\Contact::find(1);
foreach ($contact->addresses as $address) {
//
}
And for events:
$event = App\Events::find(1);
foreach ($event->addresses as $address) {
//
}
Lastly, you can retrieve Address events, contacts like so:
$address = App\Address::find(1);
foreach ($address->events as $event) {
//
}
foreach ($address->contacts as $contact) {
//
}

Categories