【问题标题】:Laravel Three-way Many-to-Many Eloquent RelationshipLaravel 三向多对多雄辩关系
【发布时间】:2018-03-28 22:21:36
【问题描述】:

我有这样的数据库
accounts

  • 身份证
  • 姓名

contacts
- 身份证
- account_id
account_communications
- 身份证
- 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');
     }
 }

账户通信模型

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 内部连接@987654332 中选择account_communications.*、accounts.contact_id @ on accounts.id = account_communications.account_id 其中accounts.contact_id in (20))

【问题讨论】:

  • 这种关系似乎很不对劲。 account_communications 是中间表吗?
  • 是的......

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


【解决方案1】:

我认为您误解了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');
   }
}

【讨论】:

    猜你喜欢
    • 2012-10-08
    • 2016-11-03
    • 2013-01-22
    • 1970-01-01
    • 1970-01-01
    • 2018-10-27
    • 1970-01-01
    • 1970-01-01
    • 2018-11-14
    相关资源
    最近更新 更多