laravel/illuminate的usewritepdo在加载关系时不受尊重

evrscar2  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(535)

我试图强制我的应用程序在运行select时使用write连接,因为处理更新数据和刷新数据的竞争条件。我已经确认正在调用usewritepdo()函数,但是我可以确定它没有使用写连接,因为竞争条件bug仍然存在。我不知道如何通过var转储来确定是否正在使用写连接。
下面是我正在运行的代码,后面是相关的模型。请注意,如果调用$portfolio->items($useWriteCon),而不是$user->portfolios($useWriteCon)->with('items'),则强制写连接是有效的。

return $this->user->portfolios($useWriteConn)->with('items')->find($id);

模型user.php:

namespace App;

use App\Notifications\ResetPassword;
use App\Support\Auth\RetrievesUser;
use Illuminate\Auth\Authenticatable;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Access\Authorizable as AuthorizableContract;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Auth\Access\Authorizable;
use Illuminate\Notifications\Notifiable;
use Laravel\Passport\HasApiTokens;

/**
 * Class User
 * @package App
 * @property integer $subscription
 * @property integer $id
 */
class User extends Model implements AuthenticatableContract,
                                    AuthorizableContract,
                                    CanResetPasswordContract
{
    use Authenticatable, Authorizable, CanResetPassword, UserTrait, Notifiable, HasApiTokens, RetrievesUser

    public function portfolios($useWriteConn = false)
    {
        return ($useWriteConn) 
            ? $this->hasMany(UserPortfolio::class, 'user')->writeConn()
            : $this->hasMany(UserPortfolio::class, 'user');
    }
}

模型userportfolio.php

namespace App;

// use App\UserCustomViews;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletes;

class UserPortfolio extends Model 
{
    use SoftDeletes;

    public function user()
    {
        return $this->belongsTo(User::class, 'user');
    }

    public function items($useWriteConn = false, $showClosed = true)
    {
        $items = $this->hasMany(UserPortfolioItem::class, 'portfolio');

        if ($useWriteConn)
            $items->writeConn();
        if (!$showClosed)
            $items->open();

        return $items;
    }

    public function scopeWriteConn($query)
    {
        return $query->useWritePdo();
    }
}

模型userportfolioitem.php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\SoftDeletes;

class UserPortfolioItem extends Model 
{

    public function portfolio()
    {
        return $this->belongsTo(UserPortfolio::class, 'portfolio');
    }

    public function scopeWriteConn($query)
    {
        return $query->useWritePdo();
    }
}
f0brbegy

f0brbegy1#

对于后来遇到这个问题的人,我从另一个线索中找到了答案。
针对db写连接的有效预加载关系

Model::onWriteConnection()->with(['relationship'=>function($query){
   $query->useWritePdo();
}])->find($id)

相关问题