Php 拉威尔通过中间表格取得了进展
考虑以下数据库方案:Php 拉威尔通过中间表格取得了进展,php,laravel,Php,Laravel,考虑以下数据库方案: companies -- id -- name logos -- id -- active -- company_id -- image_id images -- id -- filename -- path -- type 然后,我将模型中的关系定义为: Company.php public function logos() { return $this->hasMany(
companies
-- id
-- name
logos
-- id
-- active
-- company_id
-- image_id
images
-- id
-- filename
-- path
-- type
然后,我将模型中的关系定义为:
Company.php
public function logos() {
return $this->hasMany('App\Models\Logo');
}
public function image() {
$this->belongsTo('App\Models\Image');
}
public function show($id) {
$company = Company::findOrFail($id);
$requester = JWTAuth::parseToken()->toUser();
if( !$requester->hasRole('noc') && $requester->company_id != $company->id) {
return $this->response->errorUnauthorized("You have no rights to view this company profile.");
}
// I am trying to fetch it this way //
$company->logos;
foreach ($company->logos as $logo) {
return $logo->image;
}
return $this->response->array(compact('company'))->setStatusCode(200);
}
Logo.php
public function logos() {
return $this->hasMany('App\Models\Logo');
}
public function image() {
$this->belongsTo('App\Models\Image');
}
public function show($id) {
$company = Company::findOrFail($id);
$requester = JWTAuth::parseToken()->toUser();
if( !$requester->hasRole('noc') && $requester->company_id != $company->id) {
return $this->response->errorUnauthorized("You have no rights to view this company profile.");
}
// I am trying to fetch it this way //
$company->logos;
foreach ($company->logos as $logo) {
return $logo->image;
}
return $this->response->array(compact('company'))->setStatusCode(200);
}
现在我想根据它的标识和图像来确定具体的公司。因此,我尝试以这种方式获取它,但它抛出了错误:
Relationship方法必须返回Illumb\Database\Eloquent\Relations\Relationship类型的对象
CompanyController.php
public function logos() {
return $this->hasMany('App\Models\Logo');
}
public function image() {
$this->belongsTo('App\Models\Image');
}
public function show($id) {
$company = Company::findOrFail($id);
$requester = JWTAuth::parseToken()->toUser();
if( !$requester->hasRole('noc') && $requester->company_id != $company->id) {
return $this->response->errorUnauthorized("You have no rights to view this company profile.");
}
// I am trying to fetch it this way //
$company->logos;
foreach ($company->logos as $logo) {
return $logo->image;
}
return $this->response->array(compact('company'))->setStatusCode(200);
}
有人能帮我吗?:)谢谢 使用:
不起作用,抛出:
调用null上的成员函数addagerConstraints()
,这是因为您忘记将return
添加到图像
关系中。:D是的,我没有!谢谢:),我会在6分钟内接受你的回答:)酷。很高兴这有帮助。)