Reputation: 369
I have two models: User and DumpDownloadHistory. DumpDownloadHistory stores all registered Users download history. The relationship between User and DumpDownloadHistory is OneToMany. DumpDownloadHistory stores:
I need to find download history from the filter input. For example, find me all download history whose email is: '[email protected]'.
Me code:
public function history(Request $request)
{
$downloadHistory = DumpDownloadHistory::query();
if ($request->has('email') && $request->input('email') != '') {
// Find all download history related to this email
}
if ($request->has('dataset') && $request->input('dataset') != '') {
$downloadHistory = $downloadHistory->where('dataset', 'LIKE', '%'. $request->input('dataset') .'%');
}
if ($request->has('date_from') && $request->input('date_from') != '' && $request->has('date_to') && $request->input('date_to') != '') {
$datefrom = $request->input('date_from');
$dateto = $request->input('date_to');
$downloadHistory = $downloadHistory->wherebetween('created_at', [$datefrom, $dateto]);
}
if ($request->input('hasPayed') == '1') {
$downloadHistory = $downloadHistory->where('downloadCost', '!=', 'NULL');
}
$downloadHistory = $downloadHistory->get();
return view('dumpDb.history', compact('downloadHistory'));
}
User model:
class User extends Authenticatable
{
use Notifiable;
public function downloadHistorys(){
return $this->hasMany(DumpDownloadHistory::class);
}
}
DumpDownloadHistory model:
class DumpDownloadHistory extends Model
{
protected $fillable = ['dataset', 'user_ip', 'downloadCost'];
public function user(){
return $this->belongsTo(User::class);
}
}
Upvotes: 1
Views: 136
Reputation: 5358
That should do it:
if ($request->has('email') && $email = $request->input('email') !== '') {
$downloadHistory->whereHas('user', function (Builder $query) use ($email) {
$query->where('email', $email)
});
}
Take a look at the docs to read more about querying relationship existence.
Upvotes: 1