Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
354 views
in Technique[技术] by (71.8m points)

laravel - how to get the second table values in one to many relationship

I have two Models

TermOne

<?php

namespace App;

use IlluminateDatabaseEloquentModel;

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

I want to get values of this Model

<?php

namespace App;

use IlluminateDatabaseEloquentModel;

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

I want to get the table two values TermOneFile form TermOne with eager loading but I get this error:

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))

here is my Controller

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

maybe Im doing something wrong

term_one_files structure

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');
        });
    }
question from:https://stackoverflow.com/questions/65874282/how-to-get-the-second-table-values-in-one-to-many-relationship

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try specifying your foreign key in the relationship this way:

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

or you can change your column name in the migration file from: 'curriculum_id' to 'term_one_id'.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...