2017-01-07 72 views
1

我想在Laravel 5.3上建立一個應用程序,其中我的模型,數據庫和控制器位於單獨的文件夾中。我有以下文件夾結構:Laravel中的多對多關係

Nitseditor 
    System 
     Controllers 
     Database 
      2016_12_28_130149_create_domains_table.php 
      2017_01_06_193355_create_themes_table.php 
      2017_01_07_140804_create_themes_domains_table.php 
     Models 
      Domain.php 
      Theme.php 

我正在域的關係與多對多的關係,即

public function themes() 
{ 
    return $this->belongsToMany('Nitseditor\System\Models\Domain'); 
} 

我命名錶domain_theme2017_01_07_140804_create_themes_domains_table.php

現在裏面我試圖獲取屬於控制器域中的主題名稱,如下所示:

$flashmesage = new Domain; 

foreach ($flashmesage->themes as $theme) 
{ 
    return $theme->theme_name; 
} 

我得到一個錯誤:

SQLSTATE[42S02]: Base table or view not found: 1146 Table 'nitswebbuilder.domain_domain' doesn't exist (SQL: select domains .*, domain_domain . domain_id as pivot_domain_id from domains inner join domain_domain on domains . id = domain_domain . domain_id where domain_domain . domain_id is null and domains . deleted_at is null)

回答

1

對不起我的回答簡短的註釋。 ..我有意見沒有足夠的聲譽,

改變你的themes()方法:

public function themes() 
{ 
    return $this->belongsToMany('Nitseditor\System\Models\Theme'); 
} 

請參閱Here瞭解更多信息

+1

愚蠢的錯誤。謝謝你的方式! –

0

表的名字應該叫domain_theme。如果你使用外鍵corrent名,並建立了正確的關係,whereHas()會爲你工作:

$domainName = 'example.com'; 

$themes = Theme::whereHas('domains', function($q) ($domainName) { 
    $q->where('domain_name', $domainName); 
})->get(); 

然後顯示所有主題名稱:

@foreach ($themes as $theme) 
    {{ $theme->theme_name }} 
@endforeach