我有两个带透视表的表
表用户
id名称电子邮件
餐桌饮料
id名称价格
透视表user_drinks
id user_id drink_id数量价格状态
饮料模型
public function users()
{
return $this->belongsToMany('App\User', 'user_drinks', 'drink_id', 'user_id')->withPivot('price', 'quantity')->withTimestamps();
}
用户模型
public function drinks()
{
return $this->belongsToMany('App\Drink', 'user_drinks', 'drink_id', 'user_id')->withPivot('price', 'quantity')->withTimestamps();
}
我想要得到最新的用户已经购买饮料和价格和数量从透视表,例如
名为John的用户1花50美元买了2杯咖啡
名为Jane的用户2花75美元买了3杯咖啡
在用户模型中编写代码
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected $table = 'users';
protected $fillable = [
//put your users table field..
];
public function drinks() {
return $this->belongsToMany(Drink::class, 'user_drinks')->withPivot(['quantity', 'price','status']);
}
}
控制器
$userwithdrinks = User::with('drinks')->get();
echo '<pre>';
print_r($userwithdrinks->toArray());
exit;
使用此关系到用户模型
public function drinks()
{
return $this->belongsToMany(Drink::class, 'user_drinks')->withPivot(['quantity', 'price','status'])->withTimestamps();
}
要获得它:
$user = User::with(['drinks' => function ($q) {
$q->orderBy('created_at', 'desc');
}])->orderByDesc('drinks.created_at')->get();