У меня есть таблицы с отношением «многие ко многим», показанные ниже
мысль_journal_entries и эмоции. Сводная таблица think_journal_entry_emotions также находится ниже.
Как я могу использовать данные в сводной таблице для доступа к данным из обеих таблиц. Например, tj_entry_id
13 связано с em_id
3 & 5, и я хочу получить доступ к изображениям для этих идентификаторов в таблице эмоций. Как я могу сделать это в контроллере?
Они соединены этим сводная таблица
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');
}
}
Вот контроллер
$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);