What is the Eloquent equivalent of this Query Builder query? I'm trying to switch from Query Builder to Eloquent models. How can I make my model, VisualLogin, return the last activity per user id and machine id?
Here is my Query Builder equivalent:
$visualLogins = DB::connection('vmfg')
->table('LOGINS')
->select('USER_ID', 'MACHINE_ID', DB::raw('MAX(LAST_ACTIVITY) as LAST_ACTIVITY'))
->groupBy('USER_ID', 'MACHINE_ID')
->get();
You can't do more.
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class VisualLogin extends Model
{
/**
* The connection name for the model.
*
* @var string
*/
protected $connection = 'vmfg';
}
$visualLogins = VisualLogin::selectRaw('user_id, machine_id, max(last_activity) as last_activity')
->groupBy('user_id', 'machine_id')
->get();
Same except:
Logins::
In a raw you need to bind parameters, or it's unsafe.
I would put only the aggregate in raw, just example:
$quy = Powner::query()->leftJoin('dc_pets', 'dc_powners.ownerid', '=', 'dc_pets.ownerid')
->select('dc_powners.ownerid', 'dc_powners.oname')
->selectRaw('count(dc_pets.petid) as countOfPets') // here
->groupby('dc_powners.ownerid')
->orderby('dc_powners.oname')
->get();
Thanks for your help. Here is my final result based on your suggestion:
VisualLogin::select('USER_ID', 'MACHINE_ID')
->selectRaw('MAX(LAST_ACTIVITY) as LAST_ACTIVITY')
->groupBy('USER_ID', 'MACHINE_ID')
->get()
@grozavule It's same what I posted above, but it doesn't matter.
Please sign in or create an account to participate in this conversation.