问题描述
我正在使用 Laravel 和 eloquent 如果我有以下两个表
Sales
----
|id|
|--|
|1 |
|2 |
|3 |
|4 |
----
Sales_data
----
|sale_id|Product_id|
|------------|
| 1 | 30 |
| 1 | 24 |
| 1 | 18 |
| 2 | 18 |
| 2 | 30 |
| 3 | 24 |
| 4 | 18 |
| 4 | 24 |
--------------
我想检索以下信息:
| Product_id | bought_with | times_bought_together |
|--------------|-------------|-----------------------|
| 30 | 18 | 2 |
| 30 | 24 | 1 |
| 24 | 18 | 1 |
------------------------------------------------------
这是 Sales 模型中与 sale_data 的关系
public function data()
{
return $this->hasMany(\App\Models\SaleData::class,'sale_id');
}
非常感谢
解决方法
您可以使用 DB::select() 以便将 RAW SQL 语句放入其中。 在这种情况下,使用 RAW SQL 更容易
DB::select("SELECT c.product_id,c.bought_with,count(*) as times_bought_together
FROM (
SELECT a.product_id as product_id,b.product_id as bought_with
FROM sales_data a
INNER join sales_data b
ON a.sale_id = b.sale_id AND a.product_id != b.product_id) c
GROUP BY c.product_id,c.bought_with
ORDER BY times_bought_together DESC LIMIT 50")
如果你有同样的问题,祝你好运!