filter() 集合在子查询中不起作用

我正在尝试获取具有地址的用户,并且该地址的创建时间不应超过 7 天:


$users = User::whereHas('address', function($q) {

        $q->where(function ($query) {

             $query->get()->filter(function ($address) {

                 return Carbon::now() < Carbon::parse($address->getOriginal('created_at'))->addDays(7);

             });

         });

     });

作品正确,filter()但我无法返回其结果,我的结果是所有有地址的用户。


潇潇雨雨
浏览 123回答 3
3回答

繁花如伊

你可以whereDate这样使用:$users = User::whereHas('address', function ($q) {&nbsp; &nbsp; $q->whereDate('created_at', '>', Carbon::now()->subDays(7));})->get();

撒科打诨

你可以试试这样$user&nbsp;=&nbsp;User::where('address',date('Y-m-d',&nbsp;strtotime('-7&nbsp;days')))->where('created_at',date('Y-m-d',&nbsp;strtotime('-7&nbsp;days')))->get();

HUX布斯

使用注释更改您的代码$users = User::whereHas('address', function ($q): void {&nbsp; &nbsp; $q->where(function ($query): void {&nbsp; &nbsp; &nbsp; &nbsp; /**&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;* Subqueries use Eloquent Builder class here to add some wrapped filters&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;* But your code takes all addresses, filter them for nothing&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;* You should add SQL filters to builder something like that:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;**/&nbsp; &nbsp; &nbsp; &nbsp; $query->whereDate(Carbon::now()->subDays(7), '<', 'created_at');&nbsp; &nbsp; })&nbsp; &nbsp; /** To get users by your filters */&nbsp; &nbsp; ->get();
打开App,查看更多内容
随时随地看视频慕课网APP