Reputation: 71
I have to tables with a many-to-many relationship shown below
thought_journal_entries and emotions. The pivot table thought_journal_entry_emotions is also below.
How can I use the data in the pivot table to access data from both tables. For example, tj_entry_id
13 is associated with em_id
3 & 5 and I want to access the images for these id's in the emotions table. How could I do this within the controller?
They are joined by this pivot table
class Emotions extends Model
{
protected $table = 'emotions';
public $primarykey = 'id';
public function thoughtJournalEntries() {
return $this->belongsToMany(ThoughtJournalEntry::class, 'thought_journal_entry_emotions',
'em_id', 'tj_entry_id');
}
}
class ThinkingTraps extends Model
{
protected $table = 'thinking_traps';
public $primarykey = 'id';
public function thoughtJournalEntries() {
return $this->belongsToMany(ThoughtJournalEntry::class, 'thought_journal_entry_emotions',
'tt_id', 'tj_entry_id');
}
}
class ThoughtJournalEntry extends Model
{
protected $table = 'thought_journal_entries';
public $primarykey = 'id';
public $timestamps = true;
public function user() {
return $this->belongsTo('App\User');
}
public function emotions() {
return $this->belongsToMany(Emotions::class, 'thought_journal_entry_emotions',
'tj_entry_id', 'em_id');
}
public function thinkingTraps() {
return $this->belongsToMany(ThinkingTraps::class, 'thought_journal_entry_thinking_traps',
'tj_entry_id', 'tt_id');
}
}
Here is the controller
$user_id = auth()->user()->id;
$user = User::find($user_id);
$thought_journal_entries = ThoughtJournalEntry::with('emotions')->where('user_id', $user_id)->orderBy('created_at', 'desc')->paginate(15);
/*$thought_journal_entries = \DB::table('thought_journal_entries')->where('user_id', $user_id)->orderBy('created_at', 'desc')->paginate(15);*/
return view('thoughtjournal.index')->with('thought_journal_entries', $thought_journal_entries);
Upvotes: 0
Views: 55
Reputation: 1806
I believe using the with
method should help here, the so-called eager-loading. So in your controller you would do something like this:
$thought_journal_entries = ThoughtJournalEntry::with('emotions')
->where('id', 13)->get();
https://laravel.com/docs/7.x/eloquent-relationships#eager-loading
In the view you would do as follows then:
@foreach($thought_journal_entries as $entry)
{{$entry->id}}
@foreach($entry->emotions as $emotion)
{{$emotion->id}}
@endforeach
@endforeach
Upvotes: 1