mysql - 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 雄辩的查询来做到这一点。有没有可能。如果可能的话,请帮助我。
解决方案
这里 (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();
推荐阅读
- python - Prolog编程从python代码转换
- python - netCDF4 填充值行为
- c++ - 提取矩阵的对角线
- javascript - 我们如何能够在 Node.js 中使用 import 语法 (es6) 和 require (commonjs) 来导入 express 等第三方包?
- next.js - 根据 Next.js next.config.js 中的标头或 cookie 进行重定向
- reactjs - 材质 UI 无法与 Next.js 一起正常工作
- nuxt.js - asyncData 不显示 API 结果
- julia - 创建一个数组,其值符合与平均值的最小距离标准
- android - pc没有在android中询问调试授权权限
- android - Android:文件/文件夹加密