Moh*_*ara 5 localization query-builder global-scope eloquent laravel-5
我有翻译模型,我想运行全局查询范围,确定当前区域设置并返回相应的值,如果DB中不存在转换,则返回英文.
我已经为此目的创建了一个全局范围,并且它的运行良好而没有能力重新使用英语,所以有些页面崩溃,因为我试图获取NULL的属性,并且我尝试传递一些值,但在构建器中我无法确定查询是否将返回null.
怎么可能在Laravel实现这样的事情?
我的代码如下:
trait WhereLanguage {
/**
* Boot the Where Language trait for a model.
*
* @return void
*/
public static function bootWhereLanguage()
{
static::addGlobalScope(new WhereLanguageScope);
}
}
Run Code Online (Sandbox Code Playgroud)
和范围文件:
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;
});
}
Run Code Online (Sandbox Code Playgroud)
}
用法示例:
$title = $centre->translations()->whereLang()->first()->name;
Run Code Online (Sandbox Code Playgroud)
中心是我没有本地化的模型,翻译是处理Center和CentreTranslation之间关系的方法的名称.
顺便说一句我不想专门传递变量.
| 归档时间: |
|
| 查看次数: |
871 次 |
| 最近记录: |