dqxhit3376 2018-06-28 15: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-28 16: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();
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部