首页 > 解决方案 > 在原始 mysql 中编写 Eloquent 查询

问题描述

我想知道如何将这两个 Eloquent 查询写入原始 SQL?还有有没有办法将 Eloquent 系列转换为原始 SQL 系列以便我可以使用它们?

    public function items()
    {
        return $this->belongsToMany(Product::class, 'order_items', 'order_id', 'product_id')->withPivot('quantity', 'price');
    }

    public function user()
    {
        return $this->belongsTo(User::class);
    }

标签: mysqllaraveleloquent

解决方案


如果我们谈论第一个查询中使用的items方法。将其更改为原始 SQL 后,它将变为

DB::select('select `products`.*, `order_items`.`order_id` as `pivot_order_id`, `order_items`.`product_id` as `pivot_product_id`, `order_items`.`quantity` as `pivot_quantity`, `order_items`.`price` as `pivot_price` from `products` inner join `order_items` on `products`.`id` = `order_items`.`product_id` where `order_items`.`order_id` = `order_id`');

并且方法内的第二个查询user将变为

DB::select('select * from `users` where `users`.`id` = `id`');

推荐阅读