I have a laravel object where I would like to get its relations. However, the key that I would use to bind the relation could be one of two.
For example, let say I have a fictional "wine pack" which is essentially a box of three bottles of wine - either three red, three white or three rose. The "Pack" is sold as one product, but the bottles of wine can also be sold individually.
Controller.php
$wine_pack = Pack::with('wine')->get();
Wine.php
class Pack
{
public function wine()
{
return $this->belongsTo(Wine::class, 'wine_sku', 'sku');
}
}
This code actually works. But in the real world, white wine is identified by its 'sku'. Red wine and Rose wine are identified by their 'ref_id'.
I am trying to find a way to look for the individual wine by their sku, and if none are found, look by their ref_id. For example:
class Pack
{
public function wine()
{
$wine = $this->belongsTo(Wine::class, 'wine_sku', 'sku');
if($wine->count() <= 0)
$wine = $this->belongsTo(Wine::class, 'wine_ref_id', 'ref_id');
return $wine;
}
}
Is this possible?