[英]Join database tables using foreign key laravel
我有兩個表需要加入才能訪問更多數據。 我的第一個表 thought_journal_entries 包含許多來自第二個表 emotions 的 id 值。 emotions 中的主鍵是 id,thought_journal_entries 中的外鍵是 em_id。
這是在情懷 model
public function thoughtJournalEntry() {
return $this->belongsTo(ThoughtJournalEntry::class, 'id');
}
這是在 ThoughtJournalEntry model
public function emotions() {
return $this->hasMany(Emotions::class, 'id');
}
這是我得到的結果,不確定這是否正確以及我將如何在 controller 中加入這些?
如果在thought_journal_entries
表中設置em_id
,則意味着 thoughtJournalEntry 屬於 Emotions,而 Emotions 有許多 thoughtJournalEntry,所以在這種情況下關系必須這樣聲明
// Emotions class
public function thoughtJournalEntries() {
return $this->hasMany(ThoughtJournalEntry::class, 'em_id');
}
// ThoughtJournalEntry class
public function emotion() {
return $this->belongsTo(Emotions::class, 'em_id');
}
// access from controller
$emotion->thoughtJournalEntries;
$thoughtJournalEntry->emotion;
如果這種類型的關系不是您想要的,那么您可能必須更改數據庫表
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.