If a have a "product" model that has a field code that has a one-to-many relationship with a "variation" table that has also a code field. How can I use eloquent to select the row if code value of either table has some value.
How could I do something like this:
select * from product inner join variation on product.id = variaction.product_id where product.code = "code" or variation.code = "code".
Consider your Product and Variation models looks like these:
class Product extends Model
{
protected $table = 'product';
public function variation()
{
return $this->belongsTo('App\Variation', 'product_id', 'id');
}
}
class Variation extends Model
{
protected $table = 'variation';
public function products()
{
return $this->hasMany('App\Product', 'id', 'product_id');
}
}
You can obtain the data with Eloquent like this:
$code = 'code';
Product::where('code', '=', $code) // for product table
->orWhereHas('variation', function($query) use ($code) {
$query->where('code', '=', $code); // for variation table
});