【问题标题】:how to make relation between two tables in laravel如何在laravel中建立两个表之间的关系
【发布时间】:2021-08-06 13:58:33
【问题描述】:

我尝试了互联网和 Youtube 上的所有教程,但都不起作用,所以你们是我最后的机会了,我需要你们的帮助。

我需要使用 $candidate->service->service_name$candidate->documents->doc 但它不起作用 我收到此错误[Call to undefined method stdClass::service()] (顺便说一句,我应该使用“documents”还是“document”?)

“候选人”拥有多个文档,且该文档仅属于一个“候选人”;

“候选人”必须选择一项“服务”(工作),并且该服务被很多“候选人”选择

我有 3 张桌子:

服务=['id_service', 'service_name'] #((id_service 主键))

候选人 =[ 'id_candidate', 'id_service', '姓名', '电子邮件'...]; #((id_candidate Primary key, id_service Foreign key))

document=['id_doc', 'id_candidate', 'doc'] #((id_doc Primary key, id_candidate Foreign key))

在候选人的模型中:

 use App\Models\Service;
 use App\Models\Document;
 public function documents()
{     
 return $this->hasMany(Document::class);
}
public function service()
{
    return $this->belongsTo(Service::class);
}

在文档模型中:

use App\Models\Candidate;
public function candidate()
{
    return $this->belongsTo(Candidate::class, 'id_candidate', 'id_doc');
}

在服务模式中:

use App\Models\Candidate;
public function candidates()
{
    return $this->hasMany(Candidate::class);
}

在候选控制器中:

public function show( $id_candidate)
{
    $candidate = DB::table('candidates')->select('id_candidate','id_service','name')->where('id_candidate', $id_candidate)->first();

    return view ('candidate.profile', compact('candidate'));
}

IN 候选人/个人资料: ...

   <input type="text" id="service" name="service" value={{ $candidate->service()->service_name }}>

你是我的希望 提前谢谢你

【问题讨论】:

  • "但它不起作用" 什么不起作用?您如何访问数据?
  • 我收到此错误 [Call to undefined method stdClass::service()] @brombeer
  • 请分享更多细节。给定代码中没有任何内容调用该方法
  • 现在呢? @NicoHaase
  • 当您进行DB:: 调用时,Eloquent 关系将不存在,因为您正在绕过 Eloquent。你应该做类似$candidate = Candidate::find($id_candidate)的事情;您还应该停止使用默认结构。 Laravel 期望 ID 为 id,而不是 id_candidate

标签: php eloquent laravel-8


【解决方案1】:

候选模特

class Candidate extends Model
{
    public function candidate_documents()
    {
        return $this->hasMany(Document::class, 'id_candidate');
    }
    public function candidate_service()
    {
        return $this->BelongsTo(Service::class, 'id_service');
    }
}

@ceejayoz 评论说,使用 DB:: 关系不起作用 所以从候选控制器你可以像这样使用它

$candidateResult= Candidate::with('candidate_documents')->with('candidate_service')->get();

你也可以在 Candidate_service() 中使用 hasOne 取决于你的外键在哪里 在您的代码中,Candidate 有一个 id_service 列,然后是 Candidate belongsTo Service。

通过使用 hasOne 和 hasMany,我们告诉 laravel 这个表没有外键。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-17
    • 2023-03-29
    • 2019-01-20
    相关资源
    最近更新 更多