dqxhit3376 2018-06-28 23:48
浏览 87
已采纳

Laravel添加功能加入

I have 2 tables, a product table and a user table.

In my users table, there's a last_login column, which returns a datetime.

In this query, I'd like to be able to create a function that would allow me to only get products if the user hasn't been online for a certain amount of time.

I was thinking of using joins for this but I'm not overly familiar with them.

Something like...

$products = Product::where("price", "<=", $maxBudget)   
        ->where('active', 1)
        ...

        ->join('users', function ($join) {
            $join->on('products.created_by', '=', 'users.id')
                 ->where('last_login', '>', 2592000);
        })
        ->get()

except this wouldn't work because last_login is a datetime so I'd need to put in a function in there like:

if ($user->last_login->diffInSeconds(Carbon::now() > 2592000) {
    do the thing
}       

How could I do this?

  • 写回答

1条回答 默认 最新

  • down2323 2018-06-29 00:01
    关注

    If you're trying to join the tables then you should be able to do something like:

    // min seconds
    $threshold = 123456;
    
    Product::query()
         ->join('users', 'products.created_by', '=', 'users.id')
         ->where('products.active', 1)
         ->where('users.last_login', '<=', now()->subSeconds($threshold)->toDateTimeString())
         ->select(['products.*', 'users.last_login'])
         ->get();
    

    Otherwise if it's based on the logged in user's last_login:

    // Get the user's last login attribute.
    $lastLogin = auth()->user()->last_login;
    
    // whatever the minimum time since their last login should be.
    $threshold = 12345; 
    
    $exceeded = now()->diffInSeconds(Carbon::parse($lastLogin))->gte($threshold);
    
    if ($exceeded) {
        Product::where(...)->get();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?