如何在mysql中建立数据库关系并与join配合使用雄辩

时间:2019-07-18 11:55:20

标签: php mysql eloquent slim

我有三个数据库表

客户

customer_id(int), customer_name(varchar)
     1                  Business name

产品

product_id(int), customer_id(int), product_name(varchar),  qty
    1                   1               Paper Glass        100
    2                   1               Pizza Boxex        100

送货

delivery_id(int), customer_id(int), delivery_number(varchar)
     1                   1                 b-2321

delivered_items(此表包含一个交货的多个产品)

delivery_id, product_id, delivered_qty
      1           1           23
      1           2           68

我要显示html表

Delivery Number, delivered products, Delivery Date etc... 

我的代码是:

我以此来检索客户(客户1)的交货

SELECT * FROM
delivery t1 
INNER JOIN 
customers t2 ON t1.customer_id = t2.customer_id
WHERE t1.customer_id = 1; 

我正在尝试使用此代码来获取已交付的物品。

SELECT *
FROM
delivery_items t1 
INNER JOIN 
delivery t2 ON t1.delivery_id = t2.delivery_id
INNER JOIN
products t3 ON t1.product_id = t3.product_id
WHERE t1.delivery_id = 1;

我的问题是,如何从php中以前的结果中获取delivery_id(请参见下面的代码),并在同一视图中显示交付的产品。

public function getCustomer($request, $response)
{
    $id = $request->getAttribute('id');
    $data['customer'] = Customer::where('customer_id', $id)->first();
    $data['delivery'] = $this->db->table('delivery')->join('customers', 'delivery.customer_id', '=', 'customers.customer_id')->select('delivery.delivery_id', 'delivery.delivery_number', 'delivery.status', 'delivery.created_at', 'customers.customer_id', 'customers.business_name')->where('customers.customer_id', $id)->get();

    if (!$data['customer']) {
        $this->flash->addMessage('error', 'Nothing delivered to this customer.');
        return $response->withRedirect($this->router->pathFor('customers.customers'));          
    }

    return $this->view->render($response, 'customers/customer.twig', $data);
}

我不知道如何检索交货的交货产品。当我在联接中包含delivery_items表时,我得到了重复的相同传递。

我希望我能解释...

0 个答案:

没有答案