首页 文章

Laravel三向多对多雄辩的关系

提问于
浏览
0

我有这样的数据库
accounts

  • id

  • 名字

contacts

  • ID
  • 帐户ID
    account_communications
  • ID
  • 帐户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来自accounts.id = account_communications.account_id中的account_communications内连接帐户 . contact_id in(20))

1 回答

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

相关问题