我有翻译模型,我想运行确定当前语言环境的全局查询范围,并在其上返回相应的值,或者如果数据库中不存在翻译,则返回英文。
我为此目的创建了一个全局范围,并且它运行良好,但无法退回到英语,因此一些页面崩溃,因为我试图获取 NULL 的属性,并且我尝试传递一些值,但在构建器内部我无法确定查询是否将返回 null。
如何在 Laravel 中实现这样的事情?
我的代码如下:
trait WhereLanguage {
/**
* Boot the Where Language trait for a model.
*
* @return void
*/
public static function bootWhereLanguage()
{
static::addGlobalScope(new WhereLanguageScope);
}
}
和范围文件:
class WhereLanguageScope implements ScopeInterface {
/**
* Apply the scope to a given Eloquent query builder.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @param \Illuminate\Database\Eloquent\Model $model
*/
public function apply(Builder $builder, Model $model)
{
$this->addWhereLang($builder);
}
/**
* Remove the scope from the given Eloquent query builder.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
* @param \Illuminate\Database\Eloquent\Model $model
*
* @return void
*/
public function remove(Builder $builder, Model $model)
{
$query = $builder->getQuery();
foreach ((array) $query->wheres as $key => $where)
{
// If the where clause is a soft delete date constraint, we will remove it from
// the query and reset the keys on the wheres. This allows this developer to
// include deleted model in a relationship result set that is lazy loaded.
if ($where['column'] == 'lang_id')
{
unset($query->wheres[$key]);
$query->wheres = array_values($query->wheres);
}
}
}
/**
* Extend Builder with custom method.
*
* @param \Illuminate\Database\Eloquent\Builder $builder
*
*/
protected function addWhereLang(Builder $builder)
{
$builder->macro('whereLang', function(Builder $builder)
{
// here 1 is ID for English,
// 48 Arabic, 17 Netherlands...etc
// and It was the App:currentlocale() passed into Language model to determine the ID of current locale.
// but for testing now I hard coded it with ID of 48
$builder->where('lang_id','=','48');
return $builder;
});
}
}
使用示例:
$title = $centre->translations()->whereLang()->first()->name;
其中 Center 是我没有本地化的模型,translation 是处理 Center 和 CentreTranslation 之间关系的方法的名称。
顺便说一句,我不想强制传递变量。