简体   繁体   中英

Laravel Eloquent and Query Builder “with (nolock)”

I have some throuble because my queries not have with (nolock) instruction after from clause.

Because that, some queries lock the database and then nobody can use the system.

How to use with (nolock) with Eloquent & Query Builder?

For example.. in this query:

return static::with('campaignType')
    ->where('active', 1)
    ->get();

I want the follow result:

select
    *
from campaigns with (nolock)
inner join campaign_types with (nolock) on campaign_types.id = campaigns.campaign_type_id 
where campaigns.active = 1 

Here is how I deal it with eloquent (Tested on Laravel 5.1 and 5.2)

You need to add scope in your model:

public function scopeNoLock($query)
{
    return $query->from(DB::raw(self::getTable() . ' with (nolock)'));
}

Then you can call it like

return Model::noLock()->get();

您可以像这样设置“with(nolock)”:

DB::table('campaigns')->lock('WITH(NOLOCK)')

Easy way:

/**
 * @param $query
 * @return $this
 */
public function scopeNoLock($query)
{
    return $query->from($query->getQuery()->raw(self::getTable() . ' with (nolock)'));
}

您也可以使用带有方法sharedLock的本机解决方案

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM