【发布时间】:2018-01-26 17:00:58
【问题描述】:
我在将以下 MySQL 查询转换为 Laravel (5.5) Eloquent 查询生成器时遇到问题。
$start = '2018-01-22'; // Some random starting point for the Query
$query = "SELECT * FROM cdr c WHERE soort=3 AND con_duur > 0 AND con_duur
>= (select kortbel_seconden from queue q where q.queue_id=c.queue_id) AND `start_tijd >= '$start'";`
我有以下型号:
// CDR 模型
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class CDR extends Model
{
protected $table = 'cdr';
protected $primaryKey = 'cdr_id';
public function Queue()
{
return $this->hasOne('App\Models\Queue', 'queue_id', 'queue_id');
}
}
// 队列模型
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Queue extends Model
{
protected $table = 'queue';
protected $primaryKey = 'queue_id';
public function cdr()
{
return $this->belongsTo('App\Models\CDR', 'queue_id', 'queue_id');
}
}
到目前为止,我的控制器中有以下代码:
App\Models\CDR::with('queue')
->where('soort', '3')
->where('con_duur', '>', '0')
->where('start_tijd', '>=' , $start)
->where('con_duur', '>=', ' ') // this is where the sub select from the `queue` table should be : (select kortbel_seconden from queue q where q.queue_id=c.queue_id)
->get();
我被子选择卡住了,有没有办法用 Laravel 的查询生成器来做到这一点?
谢谢!
【问题讨论】:
-
你想使用 DB:raw() 方法吗?请在此处查看原始表达式。 laravel.com/docs/5.5/queries#raw-expressions 第一个例子可能对你有帮助。
-
@Kristiyan 感谢您的回复。我不介意使用 DB::raw() 方法。我仍然不明白这将如何工作。我去过 Laravel 文档并且知道 DB::Raw(),但它仍然是关系表上的一个选择。我已经用 join() 解决了另一个查询,但是 CDR 表可能会变得非常大,我不想吃掉所有的内存。