首页 > 解决方案 > laravel eloquent ORM如何进行三维关系查询?

问题描述

如何通过 laravel eloquent ORM 进行三维查询?共有“buyers”、“products”、“orders”和“purchases”四个表和“buyer”、“Products”、“Orders”和“Purchases”四个模型。下面的表结构

买家表

id --- name --- email
1 ---- John --- john@example.com
2 ---- Kelly -- kelly@example.com
3 ---- Chery -- chery@example.com

产品表:

id --- name ---- quantity ---- price
1 ---- Apple --- 5Kg --------- 10$
2 ---- Orange -- 10kg -------- 11$
3 ---- Grapes -- 20kg -------- 15$

订单表:

id --- buyer_id --- status
1 ---- 1 ----------- 0
2 ---- 2 ----------- 1
3 ---- 3 ----------- 0

采购表:

id --- order_id ---- product_id --- price --- quantity --- total_price
1 ---- 1 ----------- 2 ------------ 11$ ----- 2Kg -------- 22$
2 ---- 1 ----------- 1 ------------ 10$ ----- 1Kg -------- 10$
3 ---- 1 ----------- 3 ------------ 15$ ----- 5Kg -------- 75$
4 ---- 2 ----------- 1 ------------ 10$ ----- 3kg -------- 30$
5 ---- 2 ----------- 2 ------------ 11$ ----- 4kg -------- 44$
6 ---- 2 ----------- 3 ------------ 15$ ----- 3kg -------- 45$

现在我想通过 laravel eloquent 用产品名称查询所有订单,而不是查询构建器。

$orders = Order::where('status', 0)->...........??

请帮助我如何通过 laravel 雄辩的查询来做到这一点。有没有可能。如果可能的话,请帮助我。

标签: mysqllaraveleloquent

解决方案


这里 (status = 0) => 未支付订单和 (status = 1) => 已支付订单,并且总是一个买家只有一个未支付订单。但是有更多的付费订单。

买家.php

namespace App;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Carbon\Carbon;

class Buyer extends Model
{

    /**
     * other functions and properties.
     */

    /**
     * Get the orders associated with the buyer.
     */
    public function orders()
    {
        return $this->hasMany('App\Order', 'buyer_id')->where('status', 0);
    }
}

订单.php

class Order extends Model
{

    /**
     * other functions and properties.
     */

    /**
     * Get the purchases associated with the Order.
     */
    public function purchases()
    {
        return $this->hasMany('App\Order', 'order_id');
    }
}

购买.php

class Purchases extends Model
{    
    /**
     * other functions and properties.
     */

    /**
     * Get the user product associated with the Purchase.
     */
    public function product()
    {
        return $this->belongsTo('App\Product', 'product_id');
    }
}

现在像这样查询。

$order = Order::with(['buyer', 'purchases', 'purchases.product'])->where('id', order_id)->first();

推荐阅读