将原始sql转换为laravel查询生成器

时间:2018-04-27 10:07:07

标签: php sql laravel-5

我需要帮助将此查询转换为laravel查询。

df.show
//+---+-----+
//| id| flag|
//+---+-----+
//|  1|false|
//|  2| true|
//|  3| true|
//|  4| true|
//|  5|false|
//|  6| true|
//|  7| true|
//+---+-----+

//Defining a Window over which we will call the function
import org.apache.spark.sql.expressions.Window

//No partitionBy clause so all the data will move to a single partition
//You'll also get a warning related to that
val w = Window.orderBy($"id")

//The value of `id` will be the same where `flag` is `false`
//last will be called over the window to fill the null values   
df.withColumn("new_col" , when($"flag" === lit(false) , $"id").otherwise(null))
  .withColumn("new_col" , coalesce($"new_col" , last($"new_col", true).over(w) ) )
  .show   
//+---+-----+-------+
//|id |flag |new_col|
//+---+-----+-------+
//|1  |false|1      |
//|2  |true |1      |
//|3  |true |1      |
//|4  |true |1      |
//|5  |false|5      |
//|6  |true |5      |
//|7  |true |5      |
//+---+-----+-------+

1 个答案:

答案 0 :(得分:1)

这是一个奇怪的查询,但在laravel方式它看起来像这样:

\DB::table('shelf')->where(function($query) use ($col1){
       $query->where('column1', $col1)->orWhere('column2', $col1)->orWhere('column3', $col1)->orWhere('column4', $col1)->orWhere('column5', $col1);
   })->where(function($query) use ($col2){
       $query->where('column1', $col2)->orWhere('column2', $col2)->orWhere('column3', $col2)->orWhere('column4', $col2)->orWhere('column5', $col2);
   })->where(function($query) use ($col3){
       $query->where('column1', $col3)->orWhere('column2', $col3)->orWhere('column3', $col3)->orWhere('column4', $col3)->orWhere('column5', $col3);
   })->get();