【发布时间】:2022-01-22 18:06:24
【问题描述】:
我的网站有 5 种语言
已为名称为 language 的所有表添加一列
在数据库中使用select数据时,如何在表的模型中添加where('language' , App::getLocale())查询?
范围是一种解决方案,但另一种方式
感谢您的建议
【问题讨论】:
我的网站有 5 种语言
已为名称为 language 的所有表添加一列
在数据库中使用select数据时,如何在表的模型中添加where('language' , App::getLocale())查询?
范围是一种解决方案,但另一种方式
感谢您的建议
【问题讨论】:
您可以添加全局作用域,并将作用域添加到模型的booted 方法中。
## App/Scopes/LanguageScope.php
<?php
namespace App\Scopes;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
use Illuminate\Support\Facades\App;
class LanguageScope implements Scope
{
/**
* Apply the scope to a given Eloquent query builder.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @param \Illuminate\Database\Eloquent\Model $model
* @return void
*/
public function apply(Builder $builder, Model $model)
{
$builder->where('language', App::getLocale());
}
}
在你的模型中。
## App/Models/YourModel.php
<?php
namespace App\Models;
use App\Scopes\LanguageScope;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class YourModel extends Model
{
use HasFactory;
/**
* The "booted" method of the model.
*
* @return void
*/
protected static function booted()
{
static::addGlobalScope(new LanguageScope);
}
}
因此,每当您查询记录时,where 条件将被自动添加。你可以阅读更多关于全局作用域here
【讨论】:
您可以覆盖您的语言模型 (app\Models\Language.php) 上的 newQuery() 函数
/**
* Get a new query builder for the model's table.
*
* @return \Illuminate\Database\Eloquent\Builder
*/
public function newQuery()
{
return parent::newQuery()->where('language', App::getLocale());
}
【讨论】: