Sunday, April 16, 2017

How to make Laravel belongsTo relation get data according to condition

Using Laravel 5.2, I'm trying to use belongsTo method to get data from more than one table and it should be according to a condition, such as this in Eloquent Model:

public function deals() {
    if($this->section=='offers') {
        return $this->belongsTo('App\Deals\SellOffer', 'record_id');
    } else if($this->section=='requests') {
        return $this->belongsTo('App\Deals\QuoteRequest', 'record_id');
    } else {
        return $this->belongsTo('App\Deals\Partnership', 'record_id');
    }
}

Then inside the controller just call the deals method:

    $data = Options::with('deals')->get();

The Options Table has a column called "section", this should reference to 1 of the 3 tables.

Is that possible to do this, after running the code, it always call the code inside else.



via Marwan

Advertisement