2017-01-07 18 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 

私は今2017_01_07_140804_create_themes_domains_table.php

内のテーブルdomain_theme名付けました

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

すなわち、多くの関係に多くのと、ドメイン内の関係を作っている:私は、次のフォルダ構造を持っていますコントローラのドメインに属するテーマ名を次のように取得しようとしています。

$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

$domainName = 'example.com'; 

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

そして、すべてのテーマ名を示しています。

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

変更あなたのthemes()方法に、コメントのための十分な評判を持っています

詳細はHereをご覧ください。

+1

愚かな間違いです。方法をありがとう! –

0

表名はdomain_themeと呼ばれるべきです。あなたが外部キーのcorrent名を使用しましたし、正しい関係を構築している場合は、whereHas()はあなたのために動作します:答えとして私の短いコメントして申し訳ありません

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