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);
    }
}

そしてスコープファイル:

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 の間の関係を処理するメソッドの名前です。

ところで、変数を義務的に渡したくありません。

4

0 に答える 0