Skip to content
Advertisement

Creating a subquery using laravel eloquent

My raw query is working fine but after converting it to Laravel eloquent it’s not working.

    SELECT
        key_vals.`key`,
        key_vals.`value`
    FROM
        key_vals
    WHERE TIMESTAMPDIFF(MINUTE,
            key_vals.`last_store_time`,
            now()) < (SELECT ttl from ttls) 

Advertisement

Answer

You can do the sub query and pass the result to the outer query:

$ttl = Ttl::select('ttl')->first();
$results = KeyValue::select('key', 'value')
                   ->where(DB::raw('TIMESTAMPDIFF(MINUTE, key_vals.`last_store_time`, now())'), '<', $ttl->ttl);

The inner query Ttl::select('ttl') should return a single cell value though, I just tried to do it as you mentioned in your example

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement