这是我的原始查询。如何将这个原始查询转换成Laravel雄辩的方式?
DB ::原始( “SELECT * FROM tble WHERE状态= 1,现在()之间 START_TIME和END_TIME ORDER BY ID DESC LIMIT 1”)
如何转换成Laravel这雄辩?
这是我的原始查询。如何将这个原始查询转换成Laravel雄辩的方式?
DB ::原始( “SELECT * FROM tble WHERE状态= 1,现在()之间 START_TIME和END_TIME ORDER BY ID DESC LIMIT 1”)
如何转换成Laravel这雄辩?
创建一个模型为表app/Table.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Table extends Model
{
protected $table = 'tble';
}
逻辑
$now = \Carbon\Carbon::now();
$result = \App\Table::where('status', 1)
->where('start_time', '<=', $now)
->where('end_time', '>=', $now)
->orderBy('id')
->first();
DB::table('tble')::where('status',1)
->where('start_time', '<=', Carbon::now())
->where('end_time', '>=', Carbon::now())
->orderBy('id')
->first();
您可以使用简单的日期处理包Carbon来实现此目的。
用途,其中( '状态', '=',1)代替哪里('状态',1)。 - > Laravel 5.4需要它。 –
你也可以考虑定义一个[Eloquent Model](https://laravel.com/docs/5.4/eloquent#defining-models)。例如,在这里,你的表'tble'的模型将是'Tble',然后你可以替换DB :: table('tble'):: Tble :: – ochhii
@PatrykWoziński你仍然可以传递2个参数到where子句Laravel 5.4会假定运算符是'='。 –
尝试此
DB::table('tble')::where('status',1)
->whereBetween(Carbon::now(), ['start_time', 'end_time'])
->orderBy('id')
->first();
这将打印。 从'questions'选出*,其中'status' = 1,'2017-05-22 10:08:16'在start_time和end_time之间的顺序通过'id' asc limit 1,这是错误的。 –
感谢您的详细回答,相当有用 –
此查询打印此。 select * from'questions' where'status' = 1 and'start_time'> ='2017-05-22 10:03:48'and'end_time' <='2017-05-22 10:03:48'order通过'id' asc,它返回null,即使值在这个范围之间退出 –
@KhiradBanu我的意思是检查我更新的答案。雄辩的查询之前有错误的日期比较。更改您的代码以使用我的答案中的新代码。正确的检查是'start_time <='2017-05-22 10:03:48'和end_time> ='2017-05-22 10:03:48''这在您的查询中是错误的。 – Sandeesh