Search code examples
eloquentlaravel-5.7

How can I select a row if a column value is present on the main model or the relation in Eloquent


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".

Solution

  • 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
    });