Laravel 5-相同表之间的多个关系..命名和语法

时间:2018-07-25 14:47:01

标签: laravel-5 eloquent

我有2个表(用户和公司)。用户具有不同的角色(购物者,分发者,管理员等)。我为购物者和部分分销商提供了一个可行的解决方案。我在用雄辩的语言为分销商用户设置第二种关系时遇到问题。在用户表中,我有购物者的company_id密钥。在公司表中,我有分销商的main_distributor_id键

关系:一家公司可以有多个购物者用户。一位购物者用户可以分配给一家公司。

一个公司可以有一个分销商。一个分销商可以分配给多个公司。

用户模型:

/* used for shoppers */
public function company() {
        return $this->belongsTo(Company::class);
}

/* what is the proper naming? */
public function mainDistributorCompanies() {
        return $this->belongsTo('App\Company','main_distributor_id','id');
}

公司型号:

/* for shopper users.. */
public function users() {
        return $this->hasMany(User::class, 'company_id');
}

/* What is the proper naming */
public function mainDistributorUsers() {
        return $this->hasOne('App\User','id','main_distributor_id');
}

公司负责人:

public function index(Request $request) {

/* is this the correct way to include the relationship? Naming? */
$companies = Company::with('mainDistributorUsers')->get();
return view('companies/index', compact('companies'));
}

公司索引视图:

@foreach($companies as $company)
    <tr>
        <td>{{ $company->index }}</td>
        <td>{{ $company->name }}</td>
        <td>{{ $company->address }}</td>

        <td>{{ $company->mainDistributorUsers->username }}</td> // error
        <td>{{ $company->mainDistributorUsers()->username }}</td> // error
        <td>{{ $company->username }}</td> // empty
    </tr>
@endforeach

我为分销商选择了错误的关系吗?命名错误?

1 个答案:

答案 0 :(得分:1)

您必须检查没有dag .vertex("remoteMapJournalSource(cache_AuditLog)").localParallelism(1) .vertex("sliding-window-step1").localParallelism(4) .vertex("sliding-window-step2").localParallelism(4) .vertex("map").localParallelism(4) .vertex("Offer_Recommendations").localParallelism(4) .vertex("remoteMapSink(cache_OfferRecommendations)").localParallelism(1) .edge(between("remoteMapJournalSource(cache_AuditLog)", "sliding-window-step1").partitioned(?)) .edge(between("sliding-window-step1", "sliding-window-step2").partitioned(?).distributed()) .edge(between("sliding-window-step2", "map")) .edge(between("map", "Offer_Recommendations")) .edge(between("Offer_Recommendations", "remoteMapSink(cache_OfferRecommendations)")) 的公司:

mainDistributorUsers

或使用optional()助手:

@isset($company->mainDistributorUsers)
    {{ $company->mainDistributorUsers->username }}
@endisset

顺便说一句:{{ optional($company->mainDistributorUsers)->username }} 应该是mainDistributorUsers()关系:

BelongsTo