[英]Convert MySQL query to Laravel (5.5) Query Builder
I have a problem tying to convert the following MySQL query to the Laravel (5.5) Eloquent query builder. 我在将以下MySQL查询转换为Laravel(5.5)口才查询生成器时遇到问题。
$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'";`
I have the following Models: 我有以下型号:
// CDR Model // 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');
}
}
// Queue Model //队列模型
<?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');
}
}
So far I have the following code in my Controller: 到目前为止,我的控制器中包含以下代码:
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();
I'm stuck at the point of the sub select, is there a way to do this with Laravel's Query Builder? 我被困在子选择的问题上,有没有办法使用Laravel的查询生成器来做到这一点?
Thanks! 谢谢!
Consider this code: 考虑以下代码:
DB::table('cdr AS c')
->select("*")
->where('c.soort','=',3)
->where('c.con_duur','>',0)
->where('c.con_duur','>=',function($query){
$query->select('kortbel_seconden')
->from('queue AS q')
->where('q.queue_id', '=', 'c.queue_id');
})
->where("c.start_tijd",">=",$start)
->get();
This part of the query: 这部分查询:
->where('c.con_duur','>=',function($query){
$query->select('kortbel_seconden')
->from('queue AS q')
->where('q.queue_id', '=', 'c.queue_id');
})
is used to achieve the below part of the query: 用于实现查询的以下部分:
`c`.`con_duur` >=
(SELECT
kortbel_seconden
FROM
queue q
WHERE q.queue_id = c.queue_id)
The above query results can be achieved by the following query as well through join: 以上查询结果可以通过以下查询也可以通过联接来实现:
DB::table('cdr AS c')
->select("c.*")
->join('queue AS q', 'q.queue_id', '=', 'c.queue_id')
->where('c.soort','=',3)
->where('c.con_duur','>',0)
->where('c.con_duur','>=','q.kortbel_seconden')
->where("c.start_tijd",">=",$start)
->get();
For more details you can visit: 有关更多详细信息,您可以访问:
https://laravel.com/docs/5.5/queries#where-clauses https://laravel.com/docs/5.5/queries#where-clauses
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.