我有这样的数据库
accounts
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');
}
}
帐户模型
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'字段列表'中的未知列'accounts.contact_id'(SQL:从{
account_communications
。accounts
。contact_id
{来自account_communications
{1}}accounts
=accounts
。id
account_communications
。account_id
in {20} {1}}内部联接accounts
))
答案 0 :(得分: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');
}
}