Search code examples
phplaraveleloquentrelationships

Laravel : hasOne Eloquent Relationships


I have a transactions table, which hasOne site and hasOne accounthead. But the site does not necessarily require to be bound to any transaction and the accounthead can also stand alone without being bound to any transaction.

Basically the Site and AccountHead does not necessarily belongsTo Transaction.

How can I represent this scenario using eloquent relationships.

Am I missing anything I need to do in my Site and AccountHead Model?

Here's what I have already done:

My transaction model:

    class Transaction extends Model
{
  public function site()
    {
        return $this->hasOne('App\Site');
    }
    public function accounthead()
    {
        return $this->hasOne('App\AccountHead');
    }
}

My Site Model

    class Site extends Model
{
    protected $fillable = [
        'name',
        'slug',
        'location',
        'description'
    ];
}

My AccountHead Model

class AccountHead extends Model
{
    protected $fillable = [
        'slug',
        'accountname'
        ];
}

I need to be able to display the site and the accounthead for every transactions in my view.

In my view:

 @forelse($transactions as $transaction)
     <td>{{str_limit($transaction->accounthead,47)}}</td>
     <td>{{str_limit($transaction->site,47)}}</td>
   @endforelse

Solution

  • Solved.

    It wasn't actually a one on one relationship, but was a hasMany relationship between a Site and Transaction and a AccountHead and Transaction.

    My new Site model looks like:

    class Site extends Model
    {
        protected $fillable = [
            'name',
            'slug',
            'location',
            'description'
        ];
    
     public function transactions()
        {
            return $this->hasMany('App\Transaction','site_id');
        }
    }
    

    My new AccountHead Model Looks like:

    class AccountHead extends Model
    {
        protected $fillable = [
            'slug',
            'accountname'
            ];
    
    public function transactions()
        {
            return $this->hasMany('App\Transaction','accounthead_id');
        }
    }
    

    And my new Transaction model looks like:

        class Transaction extends Model
    {
      public function site()
        {
          return $this->belongsTo('App\Site','id');
        }
        public function accounthead()
        {
          return $this->belongsTo('App\AccountHead','id');
        }
    }