Laravel 5.7从数据透视表获取数据

时间:2019-03-04 13:30:04

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

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

客户表:

---|------
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

Client.php

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

Order.php

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

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

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

谢谢。

2 个答案:

答案 0 :(得分:2)

对于客户:

$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)";
}

答案 1 :(得分:0)

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

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

这将返回给您此客户的订单数量,您只需告知其ID。