Laravel通过中间表

时间:2017-01-22 14:38:32

标签: 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('App\Models\Logo');
}

Logo.php

public function image() {
    $this->belongsTo('App\Models\Image');
}

现在我希望根据其标识和图像来获取特定公司。所以我尝试以这种方式获取它,但它抛出了错误:

  

关系方法必须返回类型为Illuminate \ Database \ Eloquent \ Relations \ Relation

的对象

CompanyController.php

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);
}

有人能帮帮我吗? :)谢谢!

1 个答案:

答案 0 :(得分:1)

使用nested eager loading

$company = Company::with('logos.image')->where('id', $id)->first();