laravel调用存在的未定义关系

时间:2017-10-24 14:06:43

标签: php laravel eloquent

 Call to undefined relationship [App\Models\Challenge] on model [App\Models\UserChallenge]

即使我已经定义了关系:

UserChallenge:

<?php

namespace App\Models;

use App\Models\Eloquent\UserChallenge as EloquentUserChallenge;

class UserChallenge extends EloquentUserChallenge {
    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function challenge()
    {
        return $this->belongsTo('App\Models\Challenge');
    }

};

挑战:

<?php

namespace App\Models;

use App\Models\Eloquent\Challenge as EloquentChallenge;

class Challenge extends EloquentChallenge {

};

3 个答案:

答案 0 :(得分:1)

我刚刚意识到->with()方法要求我引用返回关系的方法而不是引用的模型:

因此,当我更改导致问题的查询时:

$this->userChallenges()->with(Challenge::class)->latest()->limit($limit)->get();

$this->userChallenges()->with('challenge')->latest()->limit($limit)->get();

它有效。

答案 1 :(得分:1)

当您像下面这样用->withTrashed()结束关系时,也会发生这种情况:

// User model for example

public function comments() {
    return $this->hasMany('Comment')->withTrashed(); // <===
}

但是您忘记在SoftDelete模型中使用Comment

答案 2 :(得分:0)

UserChallenge模型必须引用Challenge,通常是challenge_id。然后就可以像这样使用它了

$userChallenge->challenge