Laravel三通许多一对多雄辩关系
问题描述:
我有数据库这样accounts
Laravel三通许多一对多雄辩关系
- 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
*,accounts
。contact_id
fromaccount_communications
inner joinaccounts
onaccounts
。id
=account_communications
。account_id
其中accounts
。contact_id
(20))
答
我想你误会了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');
}
}
关系映射他们似乎错了。是'account_communications'中间表吗? –
是...... – paranoid