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
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
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');
}
© 2022 - 2024 — McMap. All rights reserved.