【发布时间】: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。