【问题标题】:Laravel 5.7 Get data from Pivot TableLaravel 5.7 从数据透视表中获取数据
【发布时间】:2019-07-25 19:55:52
【问题描述】:

我正在尝试从我的数据透视表中获取数据。

客户表:

---|------
id | name
---|------
1  | John
---|------
2  | Steve

订单表:

---|------
id | description
---|------
1  | Mac
---|------
2  | Keyboard
---|------
3  | Printer

client_order(数据透视)表:

    id | client_id | order_id
    ---|-----------|------
    1  | 1           1
    ---|-----------|------
    2  | 1         | 2
    ---|-----------|------
    3  | 2         | 3

客户端.php

 public function orders()
{
    return $this->belongsToMany('App\Order','client_order');
}

订单.php

public function clients()
{
    return $this->belongsToMany('App\Client','client_order');
}

现在,我如何从数据透视表中检索数据?例如:

John | Mac, Keyboard (2 orders)
Steve| Printer (1 orders)

谢谢。

【问题讨论】:

    标签: laravel many-to-many pivot-table


    【解决方案1】:

    对于客户:

    $client = Client::find(1); //or anyway you create the client
    $client->orders; //it gives you a collection that you can get data 
    in a foreach loop
    //for example
    foreach($client->orders as $order){
        echo $order->description;
    }
    

    订购:

    $order = Order::find(1); //or anyway you create order
    $order->clients; //it gives you a collection too
    //for example
    foreach($order->clients as $client){
        echo $client->name;
    }
    

    这是给你的新评论。首先您选择您的用户,然后在一个循环中您可以获得订单:

    $clients = Client::all();
    foreach($clients as $client){
        echo $client->name." | ";
        foreach($client->orders as $order){
            echo $order->description;
        }
        echo "(".count($client->orders)." orders)";
    }
    

    【讨论】:

    • 在他们自己的查询中显示数据没关系,但是如何在单个查询中同时获取这两个表的数据,因为我需要在单个表中显示才能获取每个表的订单数客户。例如:约翰 | Mac,键盘(2 个订单) Steve|打印机(1 个订单)
    • 正是我一直在寻找的。非常感谢
    • 很高兴为您提供帮助。
    【解决方案2】:

    您可以使用@Rouhollah Mazarei 所说的关系来实现这一点,但您也可以使用自己的数据透视表来检索此信息:

    $clientsOrders = DB::table('client_order')->where('client_id', $clientId)->count()->get();
    

    这会返回给你这个客户做了多少订单,你只需要告诉他的id。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-25
      • 1970-01-01
      • 2017-10-16
      • 2019-03-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多