Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

rfsn's avatar
Level 1

Possible to create a "belongsTo" using a raw query?

I am building the following model for Eloquent. In our system we have users and each user belongs to a profile. Additionally each user also has a bunch of a clicks. We want to build able to write a custom query that will help us calculate those clicks. There's a lot of logic required to do so, but here is my setup currently:

<?php

namespace App\Models\Eloquent;

use Illuminate\Support\Facades\DB;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;

class Affiliate extends Model
{
    /**
     * The table associated with the model.
     *
     * @var string
     */
    protected $table = 'user';

    public function profile()
    {
        return $this->belongsTo('App\Models\Eloquent\Profile', 'id');
    }

    public static function clicks()
    {
        return static::modelsFromRawResults(DB::table('click')
            ->select(DB::raw('user_id, count(*) as clicks'))
            ->where('ip', '=', '100.1.12.126') // Just an example filter
            ->groupBy('user_id')
            ->get());
    }

    public static function modelsFromRawResults($rawResult = [])
    {
        $objects = [];

        foreach($rawResult as $result)
        {
            $object = new static();

            $object->setRawAttributes((array)$result, true);

            $objects[] = $object;
        }

        return new Collection($objects);
    }

I want to be able to join the user_id in the raw query to this user model so that Eloquent can interact with it.

Possible?

0 likes
0 replies

Please or to participate in this conversation.