簡體   English   中英

laravel調用存在的未定義關系

[英]laravel call to undefined relationship that exists

 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 {

};

我只是意識到->with()方法需要我引用返回關系的方法,而不是引用的模型:

因此,當我更改導致以下問題的查詢時:

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

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

有用。

當您在末尾使用->withTrashed()調用關系時,也可能發生這種情況:

// User model for example

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

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

UserChallenge模型必須具有對Challenge的引用,通常是challenge_id 然后你可以像這樣使用它

$userChallenge->challenge

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM