Laravel / Eloquent hasMany 没有外键的关系

Laravel / Eloquent hasMany relationship with no foreign key

我有一个模型 (Client) 与另一个 (Client_option) 有 hasMany 关系。

两个table在不同的数据库中(所以有一个客户端列表,然后每个客户端都有自己的数据库,里面有一个选项table)。

在我的客户端 class 中,我希望我的 options() 方法 return 选项 table 的全部内容(它知道要查找哪个客户端数据库)。事实上,我得到一个错误,因为列 client_id 在选项 table 中不存在。我当然可以创建该列并用客户的 ID 填充每一行,但我这样做只是为了 Eloquent 开心所以宁愿避免这种小混乱。

提前感谢您的任何意见!

杰夫

这将允许您将其作为关系使用,将其称为动态 属性 $user->options,使用 push 方法批量保存等等:

public function options()
{
  // it will use the same connection as user model
  $options = ClientOption::on($this->getConnectionName())->get();

  // if options model has its own, then simply
  // $options = ClientOption::get();

  $this->setRelation('options', $options);

  return $options;
}

public function getOptionsAttribute()
{
  return (array_key_exists('options', $this->relations))

    // get options from the relation, if already loaded
    ? $this->getRelation('options')

    // otherwise call the method and load the options
    : $this->options();
}