2017-10-17 156 views
0

我有數據庫這樣
accountsLaravel三通許多一對多雄辯關係

  • ID

contacts
- ID
- ACCOUNT_ID
account_communications
- ID
- ACCOUNT_ID

和接觸模型:

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

Account模型

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

AccountCommunication模型

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

在我的控制器

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

告訴我這個錯誤

SQLSTATE [42S22]:列未找到:1054未知列在 '字段列表'(SQL 'accounts.contact_id':選擇account_communications *,accountscontact_id from account_communications inner join accounts on accountsid = account_communicationsaccount_id其中accountscontact_id(20))

+0

關係映射他們似乎錯了。是'account_communications'中間表嗎? –

+0

是...... – paranoid

回答

2

我想你誤會了HasManyThrough關係,並與hasMany相混合。如果你只是看一眼了laravel HasManyThrough例如,你會得到什麼,它實際上是用於

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 

由於您的結構方式不同它被用來然後什麼更好的主意。雙方都存在account_id,那你還等什麼?

剛剛經歷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'); 
    } 
}