【问题标题】:Laravel getting belongsTo through intermediate tableLaravel通过中间表获取belongsTo
【发布时间】:2017-06-07 03:04:08
【问题描述】:

考虑以下数据库方案:

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

现在我想根据其 ID 及其徽标和图像获取特定公司。所以我试图以这种方式获取它,但它抛出了错误:

Relationship 方法必须返回 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);
}

谁能帮帮我? :) 谢谢!

【问题讨论】:

    标签: php laravel


    【解决方案1】:

    使用nested eager loading:

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

    【讨论】:

    • 不起作用,抛出:Call to a member function addEagerConstraints() on null
    • 那是因为您忘记将return 添加到image 关系中。
    • :D 是的,我是菜鸟!谢谢 :),我会在 6 分钟内接受你的回答 :)
    • 酷。很高兴它有帮助。 )
    猜你喜欢
    • 2017-03-19
    • 2020-01-15
    • 1970-01-01
    • 2019-06-27
    • 2019-02-15
    • 1970-01-01
    • 2015-11-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多