Laravel三向多对多雄辩的关系

时间:2017-10-17 09:11:28

标签: php laravel laravel-5 eloquent laravel-eloquent

我有这样的数据库
accounts

  • 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');
   }
}

帐户模型

 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_communicationsaccountscontact_id {来自account_communications {1}} accounts = accountsid account_communicationsaccount_id in {20} {1}}内部联接accounts ))

1 个答案:

答案 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');
   }
}