Laravel 查询 n+1 - 查询自定义属性关系计数
Laravel Query n+1 - Querying custom attribute relationship count
在我的用户模型上,我有以下...
/**
* @return \Illuminate\Database\Eloquent\Relations\HasManyThrough
*/
public function transactions(): HasManyThrough
{
return $this->hasManyThrough(Transaction::class, Product::class);
}
/**
* @return int
*/
public function getNumberOfOrdersInLastSevenDaysAttribute()
{
$weekAgo = Carbon::now()->subWeek();
return $this->transactions()->whereDate('transactions.created_at', '>', $weekAgo)->count();
}
当我让所有用户使用我的自定义属性甚至急切加载 事务 时,我遇到了 n+1 个问题。
我有什么选择可以忽略我的 n+1 问题?
您急于加载 transactions
关系,但 getNumberOfOrdersInLastSevenDaysAttribute
方法实际上并未使用加载的关系。它使用 transactions()
定义作为基础编写一个新查询。您可以将方法更新为 return 关系而不是计数,然后使用 withCount
方法加载计数。
public function ordersInLastSevenDays()
{
$weekAgo = Carbon::now()->subWeek();
return $this->transactions()->whereDate('transactions.created_at', '>', $weekAgo);
}
然后加载计数并访问它。
$user = User::withCount(['ordersInLastSevenDays'])->first()
$user->orders_in_last_seven_days_count
在我的用户模型上,我有以下...
/**
* @return \Illuminate\Database\Eloquent\Relations\HasManyThrough
*/
public function transactions(): HasManyThrough
{
return $this->hasManyThrough(Transaction::class, Product::class);
}
/**
* @return int
*/
public function getNumberOfOrdersInLastSevenDaysAttribute()
{
$weekAgo = Carbon::now()->subWeek();
return $this->transactions()->whereDate('transactions.created_at', '>', $weekAgo)->count();
}
当我让所有用户使用我的自定义属性甚至急切加载 事务 时,我遇到了 n+1 个问题。
我有什么选择可以忽略我的 n+1 问题?
您急于加载 transactions
关系,但 getNumberOfOrdersInLastSevenDaysAttribute
方法实际上并未使用加载的关系。它使用 transactions()
定义作为基础编写一个新查询。您可以将方法更新为 return 关系而不是计数,然后使用 withCount
方法加载计数。
public function ordersInLastSevenDays()
{
$weekAgo = Carbon::now()->subWeek();
return $this->transactions()->whereDate('transactions.created_at', '>', $weekAgo);
}
然后加载计数并访问它。
$user = User::withCount(['ordersInLastSevenDays'])->first()
$user->orders_in_last_seven_days_count