1

我正在尝试在 Laravel 5.3 上构建一个应用程序,其中我的模型、数据库和控制器位于不同的文件夹中。我有以下文件夹结构:

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]:未找到基表或视图:1146 表 'nitswebbuilder.domain_domain' 不存在(SQL:选择domains.*, domain_domain. domain_idas pivot_domain_idfrom domainsinner join domain_domainon domains. id= domain_domain. domain_idwhere domain_domain. domain_idis null and domains. deleted_atis null)

4

2 回答 2

1

抱歉我的简短评论作为答案......我没有足够的评论声誉,

将您的themes()方法更改为:

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

请参阅此处了解更多信息

于 2017-01-07T15:21:57.610 回答
0

应该叫表名domain_theme。如果您为外键使用了正确的名称并建立了正确的关系,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
于 2017-01-07T15:18:41.767 回答