【问题标题】:how to get the second table values in one to many relationship如何在一对多关系中获取第二个表值
【发布时间】:2021-01-25 03:40:49
【问题描述】:

我有两个模型

TermOne

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class TermOne extends Model
{
    public function term_one_files()
    {
        return $this->hasMany('App\TermOneFile');
    }
}

我想获取这个模型的值

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class TermOneFile extends Model
{
    public function term_ones()
    {
        return $this->belongsTo('App\TermOne');
    }
    
}

我想通过预加载从 TermOne 中获取 TermOneFile 表的两个值,但我收到此错误:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'term_one_files.term_one_id' in 'where clause' (SQL: select * from term_one_files where term_one_files.term_one_id in (1))

这是我的控制器

$curriculum = TermOne::with('term_one_files')->where('id', $request->curriculum_id)->get();

 dd($curriculum);

return view('backend.uploads.index', compact('grade', 'subject', 'term_id', 'curriculum'));

也许我做错了什么

term_one_files 结构

public function up()
    {
        Schema::create('term_one_files', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('curriculum_id');
            $table->string('filename')->nullable();
            $table->string('filepath')->nullable();
            $table->timestamps();

            $table->foreign('curriculum_id')->references('id')->on('term_ones')
            ->onUpdate('cascade')->onDelete('cascade');
        });
    }

【问题讨论】:

  • term_one_filesDB表的结构如何?
  • @ZoliSzabó 我已经上传到上面了

标签: laravel


【解决方案1】:

尝试以这种方式在关系中指定您的外键:

public function term_one_files()
{
    return $this->hasMany('App\TermOneFile', 'curriculum_id');
}

或者您可以将迁移文件中的列名从“curriculum_id”更改为“term_one_id”。

【讨论】:

    猜你喜欢
    • 2015-04-12
    • 1970-01-01
    • 2012-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-25
    • 1970-01-01
    相关资源
    最近更新 更多