gpt4 book ai didi

php - Laravel 从 Raw DB 到 Eloquent

转载 作者:行者123 更新时间:2023-11-29 00:04:29 25 4
gpt4 key购买 nike

我正在尝试将我的 Laravel 原始查询更改为 Eloquent,因为现在我已经掌握了 Eloquent 的一些基础知识,并且我已经尝试在 Laravel 中制作博客。但一些复杂性保持不变。

首先:这是我的原始 SQL:

select group_concat(DISTINCT q.sku SEPARATOR ", ") as sku, `sales_flat_order`.`status`, `sales_flat_order`.`increment_id`, `sales_flat_order`.`shipping_description`, `sales_flat_order`.`subtotal`, `sales_flat_order`.`customer_email`, `d`.`country_id`, `d`.`region`, `d`.`city`, `d`.`postcode`, group_concat(DISTINCT q.name SEPARATOR ", ") as name, concat(sales_flat_order.created_at) AS created_at from `sales_flat_order` left join `sales_flat_order_item` as `q` on `sales_flat_order`.`entity_id` = `q`.`order_id` left join `sales_flat_order_address` as `d` on `d`.`parent_id` = `sales_flat_order`.`entity_id` group by `sales_flat_order`.`increment_id` order by `sales_flat_order`.`increment_id` asc

我在 Laravel 中的原始查询:

SalesFlatOrder::leftJoin('sales_flat_order_item as q','sales_flat_order.entity_id', '=','q.order_id')
->leftJoin('sales_flat_order_address as d', 'd.parent_id', '=', 'sales_flat_order.entity_id')
->select((array(DB::Raw('group_concat(DISTINCT q.sku SEPARATOR ", ") as sku'),'sales_flat_order.status','sales_flat_order.increment_id', 'sales_flat_order.shipping_description','sales_flat_order.subtotal','sales_flat_order.customer_email','d.country_id', 'd.region', 'd.city','d.postcode',DB::raw('group_concat(DISTINCT q.name SEPARATOR ", ") as name'),DB::raw('concat(sales_flat_order.created_at) AS created_at'))))
->groupBy('sales_flat_order.increment_id')
->orderBy('sales_flat_order.increment_id')
->paginate(10);

现在我正在尝试将整个原始查询更改为 Eloquent 。我已经做了模型。因此,以下是我在 Controller 中的 Eloquent 查询。

public function detailed(){
$sales = SalesFlatOrder::with('address')->groupBy('increment_id')->orderBy('increment_id')->paginate(10);

return View::make('detailed')->with('sales', $sales);
}

我的问题:1:我确实有 group concat (Distinct q.sku) 。那么如何用 Eloquent 方式做到这一点。因为有时你需要按日期分组。或按订单分组。那么如何显示Distinct数据so sku列。那么如何将这个完整的原始查询转换为我们有 group_concat 的 Eloqeunt,DB 的这么多列是不同的

最佳答案

首先创建一个自定义集合:

$customCollection = new \Illuminate\Database\Eloquent\Collection;

然后,你可以这样做:

$user =new User;
$user->setRawAttributes((array) $userRawData);
$customCollection->add($user);

问候!

关于php - Laravel 从 Raw DB 到 Eloquent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28184849/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com