【问题标题】:One to Many Relationship with existing database. how to connect?与现有数据库的一对多关系。如何连接?
【发布时间】:2023-03-21 02:30:02
【问题描述】:

我在与现有数据库建立关系时遇到问题。

(Table1 one)
business_list (Table name)
Business_Number (PK)
name
description

(Table2 many)
setup_project (Table name)
project_id (PK)
ClientID (FK / Business_Number)
name
description

BusinessList (Model)
protected $table = 'general.business_list';
public function setupProject(){
    return $this->hasMany(SetupProject::class, 'ClientID', 'Business_Number');
}

SetupProject (Model)
protected $table = 'general.setup_project';
public function businessList(){
    return $this->belongsTo(BusinessList::class);
}

(Controller)
public function showProjects($id)
{
    $setupProject = BusinessList::findOrFail($id)->setupProject;
    return $this->showAll($setupProject);
}

这是我在邮递员中得到的,但我已经定义了本地密钥。请帮帮我。谢谢

【问题讨论】:

  • 这个邮递员错误与hasmany关系无关
  • 您收到错误,因为您使用 find 进行搜索,它从 id 搜索并且您没有 id 列
  • 是的,先生,但我已经在 hasMany 关系中添加了一个 local_key 参数。我不知道为什么会出现这个错误。

标签: laravel eloquent laravel-8 one-to-many


【解决方案1】:

我找到了答案。你需要在模型中声明你的主键。

protected $primaryKey = 'Business_Number';

【讨论】:

  • 因为当你使用 BusinessList::findOrFail($id) 它运行 select * from table where id = $id 并且你的主键与默认键不同
猜你喜欢
  • 1970-01-01
  • 2020-10-16
  • 2010-11-25
  • 2018-08-02
  • 1970-01-01
  • 2015-11-05
  • 1970-01-01
  • 1970-01-01
  • 2019-07-21
相关资源
最近更新 更多