简体   繁体   English

在Laravel上具有has_and_belongs_to_many

[英]has_and_belongs_to_many on Laravel

I'm stuck with Laravel (also new to it), readed the Many-to-Many relationship documentation and still can't find out what's my problem. 我迷上了Laravel(这也是它的新手),阅读了多对多关系文档,但仍然找不到我的问题。

I have a model Company that looks like: 我有一个模型公司,看起来像:

class Company extends Eloquent 
{
  public static $timestamps = true;

  public function owner()
  {
    return $this -> belongs_to('User', 'owner_id');
  }

  public function users()
  {
    return $this -> has_and_belongs_to_many('User', 'company_users');
  }
}

Also, I have a model User that looks like this: 另外,我有一个模型用户,看起来像这样:

class User extends Eloquent
{
  public static $timestamps = true;

  public function companies() 
  {
    return $this -> has_and_belongs_to_many('Company');
  }
}

I have a user saved to the database that has ID 1, so I do 我有一个用户保存到ID为1的数据库,所以我这样做

  $user = User::find(1);
  var_dump($user -> companies() -> get());

  $company = new Company();
  $company -> name = 'name';
  $company -> owner_id = $user -> id;

  $company -> save();

Question is, how do I save the owner inside of the users() of the company? 问题是,如何将所有者保存在公司的users()内部?

Thanks! 谢谢!

After you save your company, attach the user to it, something like this: 保存公司后,将用户附加到该公司,如下所示:

$company->users()->attach($user->id);

This will ensure that the $user->id is added to the company_users table with the $company->id 这将确保将$user->id$company->id添加到company_users表中

"Question is, how do I save the owner inside of the users() of the company?" “问题是,如何将所有者保存在公司的users()内部?”

What you have is two separate relationships that you need to keep in sync. 您需要保持同步的两个独立关系。 I would overload the save method on the Company model such that when the user_id (owner) is changed, the new owner id is added to the users relationship. 我将在Company模型上重载save方法,以便当user_id(所有者)更改时,新的所有者ID被添加到用户关系中。

// Something like this, untested, etc...
public function save()
{
    parent::save();

    if ( $this->changed( 'user_id' ) )
    {
        $this->users()->attach( $this->user_id );
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM