交易和 Eloquent
Transactions and Eloquent
我想在我的 laravel 应用程序中使用事务。但是,我很难将它们与 Eloquent.
一起使用
$user = $this -> auth -> user();
DB::transaction(function()
{
$stores_amount = $user -> stores() -> count(); #Error
});
我收到 "Undefined variable: user" 错误。我的问题是什么?如何正确使用 Eloquent 中的 SELECT 语句处理交易?
$user
不在您的回调范围内
$user = $this->auth->user();
DB::transaction(function() use ($user) {
$stores_amount = $user->stores()->count();
});
编辑
$stores_amount
仅在回调的范围内。如果您需要从事务中获取 $stores_amount
值,那么您可以声明它并将其作用域也纳入回调中,但通过引用:
$user = $this->auth->user();
$stores_amount = 0;
DB::transaction(function() use ($user, &$stores_amount) {
$stores_amount = $user->stores()->count();
});
我想在我的 laravel 应用程序中使用事务。但是,我很难将它们与 Eloquent.
一起使用$user = $this -> auth -> user();
DB::transaction(function()
{
$stores_amount = $user -> stores() -> count(); #Error
});
我收到 "Undefined variable: user" 错误。我的问题是什么?如何正确使用 Eloquent 中的 SELECT 语句处理交易?
$user
不在您的回调范围内
$user = $this->auth->user();
DB::transaction(function() use ($user) {
$stores_amount = $user->stores()->count();
});
编辑
$stores_amount
仅在回调的范围内。如果您需要从事务中获取 $stores_amount
值,那么您可以声明它并将其作用域也纳入回调中,但通过引用:
$user = $this->auth->user();
$stores_amount = 0;
DB::transaction(function() use ($user, &$stores_amount) {
$stores_amount = $user->stores()->count();
});