6

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
StayOnTarget
  • 11,743
  • 10
  • 52
  • 81
panthro
  • 22,779
  • 66
  • 183
  • 324

1 Answers1

7

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');
}
Wader
  • 9,427
  • 1
  • 34
  • 38
  • Thanks, how would I call this? I've tried Product::with('children')->find(1) but this comes back with all of the children with a color id of 1, I need to get out row 1 from products and the children should be the color id that is on row 1. – panthro Jun 02 '15 at 10:49