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 eg
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.