【问题标题】:Relating Two Tables Through One Related Table In Eloquent在 Eloquent 中通过一个相关表关联两个表
【发布时间】:2019-02-05 22:27:38
【问题描述】:

我似乎很难理解如何正确查询,因为当我尝试使用不同的运算符时,它的逻辑会变得混乱。

无论如何,我有三个表:客户、Cpe、设备。我想要来自设备的数据,但为了做到这一点,我必须使用 Customer 与 Cpe 相关联,然后将该表与 Equipment 相关联。

关系如下:

客户有很多 Cpe customerid > customerid Cpe 有一个 Equipment equipid > equipid

除了 Cpe 表之外,没有任何东西与客户和设备相关。

我特别想选择 Customer.customerid、Customer.name、Equipment.nickname、Customer.customerstatus、Customer.installationdate。但我也只想选择拥有 Equipment.nickname LIKE %SIM% 的客户。所以我所拥有的是:

$baicell_customers = Customer::with('Cpe')
->with('Cpe.Equipment')
->select('Customer.customerid', 'Customer.name', 
'Equipment.nickname', 'Customer.customerstatus', 
'Customer.installationdate' => function($query){
$query->where('Equipment.nickname', 'LIKE', '%SIM%');
})
->orderBy('Customer.name', 'asc');
->get();

但这对我没有任何帮助。我不擅长将一张表与另一张表关联起来,并且认为我必须使用相关表从另一张表获取信息对我来说简直是疯了,所以任何帮助都将不胜感激。

【问题讨论】:

  • 检查这个:Has many Through。有一篇文章可以帮到你,查看tutorial
  • @HCK 刚才我实际上正在寻找 hasManyThrough ,但我似乎无法让它工作,但如果我正确地做到这一点,它似乎可能会发生。我可能错了,但它似乎适用于 A Many > B Many > C 关系链。
  • @HCK 所以我一直在看这个大半夜以及从今天早上 8 点开始,似乎无法让它正常工作。我已将 Customer 设置为具有名为 equipment() 的函数: return $this->hasManyThrough('App\Models\Here\Equipment', 'App\Models\Here\Cpe', 'customerid', 'equipid' , 'customerid', 'cpeid');所以是 Equipment 模型,然后是 Cpe 模型,然后是客户与 cpe 的关系,然后是 cpe 与设备的关系,然后是客户和 cpe 的本地密钥。
  • 其实有一种新的关系类型适合你的情况,会在5.8版本中提供:HasOneThrough,你可以查看提交代码here

标签: php laravel eloquent


【解决方案1】:

这基本上是多对多的,您可以通过以下方式获得它。一般来说,在 Laravel 中,你会取出模型并对数据做一些事情,除非你在一个高度面向企业的系统中,否则不要用选择来做。您的命名约定也已关闭,因为 cpe 是一个数据透视表,基本上参见 Laravel Many to Many

public class Customer
{
    public equipments()
    {
        return $this->belongsToMany('App\Equipment', 'INSERT CPE TABLE NAME', 'customerid', 'equipid ');
    }
}

$customer = Customer::with('equipments')->all()->first();


foreach($customer->equipments as $equipment)
{
    $equipment->nickname;
}

即使你说 cpe 只能有一个设备,设计是多对多的,你可以做到这一点。

$equipment = $customer->equipments->first();

【讨论】:

  • 这似乎不起作用,并且表很大,因为这是一个企业的多个数据库。而且我只想让客户的设备昵称中包含“SIM”。
  • 然后你可以使用 where has 方法来获取它。但是,如果您最初甚至无法使其正常工作,那么您就处于深水中。这应该可以,错误是什么?
【解决方案2】:

所以我暂时放弃了以 Eloquent 风格做这件事。这花了一些时间,但我能够让 DB::connection('table') 查询工作。代码如下:

$baicell_customers = DB::connection('azotel')->select("SELECT distinct customers.name, customers.customerid as id, customers.installationdate, customers.customerstatus[1] as status, equipment.nickname as ap FROM  cpe INNER JOIN customers on customers.customerid = cpe.customerid INNER JOIN equipment on equipment.equipid = cpe.equipid WHERE equipment.nickname LIKE '%SIM%' order by name ASC");

这完全按预期工作,但我现在无法在 Eloquent 中正常工作,但现在没关系。如果这有助于任何人弄清楚 Eloquent 版本是什么,我仍然很想听听。否则,这个问题已经解决了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-02
    • 2014-02-14
    • 1970-01-01
    • 2016-03-31
    • 2014-08-01
    • 2020-03-18
    • 1970-01-01
    相关资源
    最近更新 更多