Laravel 5.5如何在关系中添加动态条件? [英] Laravel 5.5 How to add dynamic conditions inside a relationship?
本文介绍了Laravel 5.5如何在关系中添加动态条件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个关系可以让在特定日期创建的朋友使用静态日期参数
I have a relation to get the friends created on specific date which is working with a static date parameter
public function friends()
{
return $this->hasMany(Friend::class)->where('created_at','2018-01-31');
}
但是我需要获取一个动态日期,该日期中的$ request变量在关系内不可用.我尝试过这样的方法,
But i need to get it for a dynamic date where the $request variable is unavailable inside a relation. I tried like this which is not working
public function friends($request)
{
return $this->hasMany(Friend::class)->where('created_at',$request->date);
}
我该如何解决这个问题?
How can i solve this issue?
推荐答案
You can use Laravel helper function request()
request 函数返回当前请求实例或获取输入项
The request function returns the current request instance or obtains an input item
public function friends()
{
$date = request('date') ? : '2018-01-31'; // You can choose a default date, here '2018-01-31'
return $this->hasMany(Friend::class)->where('created_at', $date);
}
这篇关于Laravel 5.5如何在关系中添加动态条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文