简体   繁体   中英

Laravel add function to join

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?

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM