简体   繁体   中英

unable to define relationship in laravel 5.7

I have two table as sbj_topics and difficulty_level_sbj_topic so, I want to define relationship b\\w them to fetch records, so to make relationship I have done this,

SbjTopic.php:

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

And in DiffiLvlSbjTopic.php:

protected $table = 'difficulty_level_sbj_topic';
public function sbj_topics() {
    return $this->belongsTo('App\SbjTopic');
}

After that I returned the data to a view as:

$easy = DiffiLvlSbjTopic::where(['subject_id' => $id, 'difficulty_level_id' => 2])->get();
return view('diffi_lvls.show', compact('easy'));

Then in the view I done this:

@foreach($easy as $easy)
    {{ $easy->sbj_topics }}
@endforeach

but the page is blank, and when I do this {{ $easy->sbj_topics->sbj_topic_name }} trying to get property of undefined! comes.

The main purpose of creating relationship is to display Subject Topic Name because I have foreign key as sbj_topic_id in difficulty_level_sbj_topic table so if anyone has any other idea to do this without relationship that will be awesome.

Break this down:

  • SbjTopic - has many difflevels
  • a difflevel belongs to aSbjTopic

With this understanding, I can see you are getting the difflevels (DiffiLvlSbjTopic). This is actually what you are passing to your blade.

So first off: complete your relationship by specify the foreign keys. ie: In the SbjTopics model:

public function difficulty_level_sbj_topic() {
    return $this->hasMany('App\DiffiLvlSbjTopic', 'subject_id');
}

with this, you know that in the 'difficulty_level_sbj_topic' you must have the column subject_id . Now define the reverse relationship in your DiffiLvlSbjTopic model:

public function sbj_topics() {
    return $this->belongsTo('App\SbjTopic', 'subject_id');
}

With all these in place in your controller or route all you need to do is fetch the DiffiLvlSbjTopic model properties. For instance:

public function index () {
     $easy = DiffiLvlSbjTopic::all();
     return view('diffi_lvls.show', compact('easy'));
}

Finally in your view:

@foreach($easy as $difflevel)
    <div>{{ $difflevel->sbj_topics->name }} </div>
@endforeach

That's it.

Your both variables should not be $easy it can be something like $easy as $easySingle . And add a loop inside like

@foreach($easy as $easySingle)
    foreach ($easySingle->sbj_topics as $topic) {
      $topic->property;
    }   
@endforeach   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM