2017-07-28 21 views
1

我有獲取數據的問題,只有當關系查詢次數超過0.1找對象,只有當關系計數導致更多的則是0 laravel]

這是我與關係

客戶模型
class Customer extends Model 
{ 
    protected $table = 'customers'; 

    public function contracts() 
    { 
     return $this->hasMany('App\Contract'); 
    } 

這是我合同

class Contract extends Model 
{ 
    public function customer() 
    { 
     return $this->belongsTo('App\Customer'); 
    } 
} 

在最終的模式,我只需要客戶他們合約beetwen約會

$customers = Customer::with(['contracts' => function($query) 
    { 
     $query->where('data_end','>=','2017-07-01') 
       ->where('data_end','<=','2017-07-31') 
       ->where('typ','=','U') ; 
    } 
    ])->paginate(10); 

但我有所有的客戶。它看起來像這樣:

"Customer 1" 
"Customer 2" 
"Customer 3" 
    *"Contract 1" 
    *"Contract 2" 
    *"Contract 3" 
"Customer 4" 
    *"Contract 1" 
    *"Contract 2" 
    *"Contract 3" 
"Customer 4" 

在這個例子中我不需要客戶1,2和5。我如何與預先加載和對象與最終關係做到這一點。

enter image description here

這一點,我不需要客戶提供的截圖X - 我的意思是,我不需要客戶提供從那裏查詢

回答

0

使用whereHas() 0合同:

$customers = Customer::with('contracts') 
    ->whereHas('contracts', function ($q) { 
     $q->where('data_end','>=','2017-07-01') 
      ->where('data_end','<=','2017-07-31') 
      ->where('typ', U'); 
    }) 
    ->paginate(10); 
+0

這麼接近。這個查詢返回給我的只是這個客戶,他們有合同,但返回所有(「哪裏」不工作propertyly – underface

+0

@underface這只是一個例子。如果您還想在相同日期過濾合約,只需使用您的問題中的'with'部分和我的答案中的'whereHas'部分即可。它會做你想做的。 –

+0

非常感謝 – underface

0

此查詢解決我的問題

$customers = Customer::with(['contracts' => function($query) 
{ 
    $query->where('data_end','>=','2017-07-01') 
     ->where('data_end','<=','2017-07-31') 
     ->where('typ', 'U'); 
} 
])->whereHas('contracts', function ($query) { 
    $query->where('data_end','>=','2017-07-01') 
     ->where('data_end','<=','2017-07-31') 
     ->where('typ', 'U'); 
}) 
->paginate(10)