Muhamad Yulianto
Muhamad Yulianto

Reputation: 1663

Eloquent relation condition 2 columns foreign key

I have case like this

table transactions

|id|account_from_id|account_to_id|value|

table account

|id|name|type|

I would like to use eloquent relation from table account to transaction which is it need additional condition, account as from, or account as to, but in one function only relation

this is my code

public function transactions(){
    $result = $this->hasOne('App\Transactions','id', 'account_from_id');
    if(!is_null($result)){
        return $result;
    }

    return $this->hasOne('App\Transactions','id' 'account_to_id');
}

But it not work as I expected, when account as to, it will return null

Upvotes: 0

Views: 71

Answers (1)

emild_
emild_

Reputation: 93

The model column has a relation must be define on reference table and column make each column has a relation on your model

public function account_from(){
   return $this->hasOne('App\Transactions','id', 'account_from_id');
}
public function account_to(){
   $this->hasOne('App\Transactions','id', 'account_to_id');
}

define the account transaction by the new transaction attribute

public function getTransactionAttribute(){
   if(!empty($this->account_from_id)){
       return $this->account_from
   }else{
       return $this->account_to
   }
}

Upvotes: 1

Related Questions