2016-07-20 8 views
0
DB::table('New_Themes') 
       ->where('id', $id) 
       ->decrement('upVotes', 1); 
       DB::table('New_Themes') 
       ->where('id', $id) 
       ->increment('downVotes', 1); 
... 

私は更新クエリを持っていますので、少なくとも4つあります(ここで増分されたもの)が繰り返しあり、オンに検索するのに時間がかかります。Laravel、更新クエリとFirstorCreateメソッド

私の質問:ありそう

DB::table('New_Themes') 
       ->where('id', $id) 
       ->decrement('upVotes', 1); 
       ->increment('downVotes', 1); 

を行うなどの任意のショートカットがあるが、それは、それを簡単にする方法任意のアイデアを動作しませんか?

2番目の質問: firstArCreateメソッドをLaravelで使用するには、コードを簡単にするためにこの機能が必要です。しかし、私はそれをモデル、コントローラとどのように統合するのか分かりません。

Ex. $flight = App\Flight::firstOrCreate(['name' => 'Flight 10']); (from documentation) 

$飛行、ブールか...?ある変数のどのような、任意の説明は、私にとって非常に役に立つことlaravelのドキュメントは、詳細な情報が欠けている原因となります。

+0

を見ることができます。 –

答えて

1

1.

function downVote($id) 
{ 
     DB::table('New_Themes') 
      ->where('id', $id) 
      ->decrement('upVotes', 1) 
      ->increment('downVotes', 1); 
} 

次に、あなたが複数回、それを使用している場合、それを入力する必要はありません。

2.

$飛行モデル飛行のインスタンスである、あなたは、モデルを使用する方法を学ぶ必要があるデータを扱うとき、これはあなたの人生を容易にし、完全にLaravelsドキュメントが非常によくあるMVCアーキテクチャを使用それについて文書化されています。

+0

それは私に言う:構文エラー、予期しない ' - >'(T_OBJECT_OPERATOR)、なぜこれが起こる? – DomainFlag

+0

これは私が以下の - > increment( 'downVotes'、1)を追加すると起こります。 – DomainFlag

+0

私はこのfinnaly DB :: table( 'New_Themes') - >ここで( 'id'、$ id) - >更新(['upVotes' => DB :: raw( 'upVotes - 1')、 'downVotes' => DB :: raw( 'downVotes + 1')、 ]);非常にうまくいく – DomainFlag

1
/** 
    * Get the first record matching the attributes or create it. 
    * 
    * @param array $attributes 
    * @return static 
    */ 
    public static function firstOrCreate(array $attributes) 
    { 
     if (! is_null($instance = static::where($attributes)->first())) 
     { 
      return $instance; 
     } 

     return static::create($attributes); 
    } 

あなたはそれが作成/更新された要素の対象になりますファイルvendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php