2017-08-09 130 views
0

我的查询:Laravel whereHas返回意外的结果

Description::whereHas('expenses', function($query) { 
     $query->where('date', $this->date); 
    })->with('expenses')->get(); 

上述查询返回给定日期的所有描述,但它返回的所有费用为说明,而不是在指定日期的费用。我不明白这是为什么,我想首先理解这一点。这是因为with('expenses')我只是渴望加载每个描述的所有费用?而且,我只是返回给定日期至少有一笔费用的所有描述?

如果以上所有内容都属实,我如何才能返回给定日期的所有说明,包括给定日期的费用?

描述型号:

public function expenses() 
{ 
    return $this->hasMany(Expense::class); 
} 

费用型号:

public function description() 
{ 
    return $this->belongsTo(Description::class); 
} 
+1

的[合并 '与' 和在Laravel 5 'whereHas'](https://stackoverflow.com/questions/29591931/merge-with-and-wherehas-in-laravel-5) – Maraboc

回答

1

您是仅Description对象应加载过滤。您应该将相同的过滤器应用于预先加载,以便只将这些过滤器添加到模型中。

Description::whereHas('expenses', function($query) { 
     $query->where('date', $this->date); 
    }) 
    ->with([ 
     'expenses' => function($query) { 
      $query->where('date', $this->date); 
     } 
    ]) 
    ->get(); 
+0

可能的复制我想这会是这么简单.. – Hardist