未定义的属性:Illuminate \ Database \ Eloquent \ Relations \ BelongsTo :: $ diffi_lvl_name

时间:2019-01-25 12:31:39

标签: php laravel

在建立关系时,我在 Laravel 5.7 中遇到错误,我创建的关系如下: Question.php:

public function diffi_lvl() {
    return $this->belongsTo('App\DifficultyLevel');
}

DifficultyLevel.php:

public function questions() {
    return $this->hasMany('App\Question');
}

之后,我使用了

@foreach ($questions as $question)
    {{ dd($question->diffi_lvl()->diffi_lvl_name) }}
@endforeach

QuestionController.php:

public function index()
{
    $questions = Question::all();
    return view('questions.index', compact('questions'));
}

困难级别迁移:

public function up()
{
    Schema::create('difficulty_levels', function (Blueprint $table) {
        $table->engine = 'InnoDB';
        $table->increments('id');
        $table->string('diffi_lvl_name');
        $table->timestamps();
    });
}

和问题迁移:

public function up()
{
    Schema::create('questions', function (Blueprint $table) {
        $table->engine = 'InnoDB';
        $table->increments('id');
        $table->text('question');
        $table->unsignedInteger('difficulty_level_id');
        $table->foreign('difficulty_level_id')->references('id')->on('difficulty_levels');
        $table->timestamps();
    });
}

但是它给了我这个错误:

未定义的属性:Illuminate \ Database \ Eloquent \ Relations \ BelongsTo :: $ diffi_lvl_name

  

注意::我还使用了{{ dd($question->diffi_lvl->diffi_lvl_name) }}来获取试图获取非对象的属性

2 个答案:

答案 0 :(得分:1)

您已经使用

解决了第一个错误
$question->diffi_lvl->diffi_lvl_name

对于第二个错误,有一些可能性。

  • 问题模型没有附加DifficultyLevel
  • 我们必须查看您的表结构。也许您错误地映射了外键。“问题”表中的外键名为“ difficulty_level_id”吗?

答案 1 :(得分:1)

按如下所示更改您的关系:

IIF(SimpleLoan=0,0,transDemand.SimpleInstallment,IIF(transDemand.SimpleInstallment=0,select Installment from LoanMaster where FYear=(select max(FYear) from LoanMaster),0)) AS SimpleInstallment

然后,以下方法应该起作用:

public function diffi_lvl() {
    return $this->belongsTo('App\DifficultyLevel', 'difficulty_level_id');
}

public function questions() {
    return $this->hasMany('App\Question', 'difficulty_level_id');
}

有关更多信息,请阅读Defining Relationships.

上的文档

编辑:实际上,似乎只需执行以下操作即可

@foreach ($questions as $question)
    {{ dd($question->diffi_lvl->diffi_lvl_name) }}
@endforeach