Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Self Join in Eloquent

How would you write a self join in eloquent? Would I need to define the relationship on the model?

Here's my statement:

SELECT t2.title FROM products t1, products t2
WHERE t1.id = $id 
AND t2.color_id = t1.color_id AND
t2.id != $id
like image 712
panthro Avatar asked Jun 02 '15 09:06

panthro


1 Answers

You can simply define a relation to itself.

public function parent()
{
    return $this->belongsTo(self::class, 'color_id');
}

public function children()
{
    return $this->hasMany(self::class, 'color_id');
}
like image 117
Wader Avatar answered Nov 13 '22 13:11

Wader