paranoid
paranoid

Reputation: 7105

Laravel Three-way Many-to-Many Eloquent Relationship

I have database like this
accounts

contacts
- id
- account_id
account_communications
- id
- account_id

and contact model :

class Contact extends Model
{ 
    public function Account()
    {
       return $this->belongsTo('App\Account');
    }
   public function AccountCommunication()
   {
      return $this->hasManyThrough( 'App\AccountCommunication','App\Account');
   }
}

Account model

 class Account extends Model
 {
     public function AccountCommunication()
      {
          return $this->hasMany('App\AccountCommunication');
      } 
    public function Contact()
    {
        return $this->hasMany('App\Contact');
     }
 }

AccountCommunication model

class AccountCommunication extends Model
 {
      public function Account()
     {
          return $this->belongsToMany('App\Account');
      }
  }

On my controller

class ContactController extends Controller
  {
     public function index()
     {
        $contacts = Contact::with('Account')->with('AccountCommunication')->paginate(10);
      dd($contacts);
     }
  }

Show me this error

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'accounts.contact_id' in 'field list' (SQL: select account_communications.*, accounts.contact_id from account_communications inner join accounts on accounts.id = account_communications.account_id where accounts.contact_id in (20))

Upvotes: 0

Views: 147

Answers (1)

Basheer Kharoti
Basheer Kharoti

Reputation: 4302

I think you have misunderstood the HasManyThrough relationship and mixing it with hasMany. If you just look at glance over laravel HasManyThrough example, You would get better idea of what it actually is used for

countries
  id - integer
  name - string

users
    id - integer
    country_id - integer --> here is the key role for countries posts
    name - string

posts
    id - integer
    user_id - integer
    title - string

Since your structure is way different then what it is being used for. The account_id exists on both side so what are you waiting for then?

Just map them through account_id e.x

class Contact extends Model
{ 
    public function Account()
    {
       return $this->belongsTo('App\Account');
    }
   public function AccountCommunication()
   {
      return $this->hasMany( 'App\AccountCommunication', 'account_id', 'account_id');
   }
}

Upvotes: 2

Related Questions