我应该在Laravel的多个模型中使用什么雄辩的关系

问题描述 投票:1回答:1

我正在查看订单ID中的某个订单库。我显示连接到订单的公司没有问题,但后来我意识到我还需要显示该公司的联系人,他们已经订购我需要在视图中显示。

在挖掘时我了解到我可以使用hasManyThrough但不知道如何实际显示数据。我甚至不确定hasManyThrough能否提供我需要的东西。

这是简化的表关系;

Companies                Contacts                 Orders
   id                  companies_id             company_id

联系人表格屏幕

enter image description here

公司表

enter image description here

订单表

enter image description here

公司模式

public function orders()
{
    return $this->hasManyThrough(
        Orders::class, 
        Contacts::class, 
        'companies_id', 
        'company_id', 
        'id', 
        'id' 
    );
}    

订单模型

public function companies()
{
   return $this->hasOne('App\Companies', 'id','company_id');
}

public function contact()
{
   return $this->hasOne('App\Contacts', 'id','companies_id');
}

我试图显示这样的数据

<div class="col-xs-6">
    <strong>TO:</strong>
    <h4>{{ $orders->companies->comp_name }}</h4> //this is ok
    <p>{{ $orders->companies->comp_address }}</p> //this is ok
    <p>{{ $orders->contact['cont_name'] }}</p> //this should be the contact person from that company
</div>

关于如何实现这一目标的任何建议?非常感谢你!

laravel relation
1个回答
1
投票

你需要hasManyThrough在Cascade 1对多对多的风格。就像艺术家有很多专辑有很多歌,所以艺术家通过专辑(艺术家 - >专辑 - >歌曲)有很多歌。

在你的情况下:

1-公司有一个或多个联系人,假设您将使用业务逻辑代码将其限制为1

2-公司有多个订单,订单属于公司

3- A联系人属于公司

所以你可以使用代码:

更新-----

正如您在注释中指定的那样,公司可以拥有多个联系人,那么您可以为联系人定义额外的hasMany关系。


在公司模型中

<?php
// Companies model

public function contact()
{
   return $this->hasOne('App\Contacts', 'companies_id');
}

public function contacts()
{
   return $this->hasMany('App\Contacts', 'companies_id');
}

public function orders()
{
   return $this->hasMany('App\Orders', 'company_id');
}

在联系模型中

<?php
// Contacts model
// Keep it singular since it's only one Company
public function company()
{
   return $this->belongsTo('App\Companies', 'companies_id');
}

在订单模型中

<?php
// Orders model
// Keep it singular since it's only one Company
public function company()
{
   return $this->belongsTo('App\Companies', 'company_id');
}

最后在Blade视图中

<div class="col-xs-6">
    <strong>TO:</strong>
    <h4>{{ $orders->company->comp_name }}</h4> //this is ok
    <p>{{ $orders->company->comp_address }}</p> //this is ok
    <p>{{ $orders->company->contact->cont_name }}</p> //this should be ok
</div>
© www.soinside.com 2019 - 2024. All rights reserved.