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

nine's avatar
Level 1

complexe sql query

hy,

i have this sql query :

SELECT DISTINCT * FROM image_models t1 WHERE EXISTS ( SELECT * FROM image_models t2 WHERE t1.ID <> t2.ID AND t1.hashkey = t2.hashkey )

what is the best/safe way to use it in my project ?

I'm trying with this :

$results = DB::select( DB::raw("SELECT DISTINCT * FROM image_models t1 WHERE EXISTS (SELECT * FROM image_models t2 WHERE t1.ID <> t2.ID AND t1.hashkey= t2.hashkey") );

but i'm getting this error :

`SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' ``

thank you

0 likes
5 replies
aurawindsurfing's avatar

Hi,

I would imagine your code should look like this:

$results = DB::raw(
"SELECT DISTINCT * FROM image_models t1 WHERE EXISTS 
(SELECT * FROM image_models t2 WHERE t1.ID <> t2.ID AND t1.hashkey= t2.hashkey")
);

But still making those raw select statements looks just ugly to me ;-) Why not use Eloquent?

If you create Models for it then you can encapsulate those methods

public function t2Hash()
    {
        return $this->belongsTo(T2::class);
    }

and have something that just reads nicely like so:

$results = Image::t2Hash()->get();

And then you do another where and so on until you get what you want.

You get the idea.

nine's avatar
Level 1

i finnaly get it working with this :

` return DB::select("SELECT DISTINCT * FROM image_models t1 WHERE EXISTS (SELECT * FROM image_models t2 WHERE t1.ID <> t2.ID AND t1.hashkey= t2.hashkey)"); ``

and yes i would prefer use eloquent ! but i don't find the way :-(

thx if you can put me in the right way ;-)

nine's avatar
Level 1

i think i get the idea , thx ;-)

Please or to participate in this conversation.