2017-07-28 78 views
0

我有以下与正常工作的子查询工作查询我想transfrom以雄辩的,因为我想坚持我的用户模型的其他relaiont将原始查询与子查询侃侃而谈

select * from (
select p.from, a.account_id, count(*) as num 
from accounts as a 
inner join accounts_prop as p on (a.account_id = p.account_id) 
group by p.account_id 
having num = 1) query 

where year(query.von) = 2017 

我已经有由(表accounts)表示的用户模型,并通过(properites表)

User -> Property关系所表示的属性的模型是一对多

用户

public function properties() 
{ 
    return $this->hasMany('App\Property', 'account_id', 'account_id'); 
} 

物业

public function user() 
    { 
     return $this->belongsTo('App\User', 'account_id'); 
    } 

输出应该归还它有一个属性和属性当前日期相匹配的所有用户。

在我的测试目的原始查询我所用恒定的一年

+0

工作,请发表您的表结构和发布查询您的预计产量。 –

回答

0

其实好像

User::whereHas('properties', function($query){ 

      $query = $query->where('von', '=', Carbon::now()->format('Y-m-d')) 
          ->havingRaw('count(account_id) = 1') 
          ->with('department'); 

     })->get();