将RAW Eloquent查询与Slim PHP一起使用


Use RAW Eloquent Queries with Slim PHP

我正在使用SlimPHP和Eloquent进行一个项目。我正在尝试在Model的方法中运行RAW SQL查询,如下所示:

/型号/Form.php

<?php
namespace models;
class Form extends 'Illuminate'Database'Eloquent'Model {
protected $table = 'forms';
public function getResponses($form_id)
{
    // HERE
    $select = 'Illuminate'Support'Facades'DB::select('select 1');
    return 1;
}
}

我正在使用Capsule引导ORM。

上面的代码给了我:

致命错误:在中的非对象上调用成员函数select()/流浪者/供应商/照明/支持/照明/支撑/立面/立面.php在线208

在这种情况下,文档很有帮助,你能说明一下吗?

感谢

仔细阅读github上的设置说明,并确保正确遵循。


使用Capsule时,应使用Illuminate'Database'Capsule'Manager或作为DB"Facade"。

$select = 'Illuminate'Database'Capsule'Manager::select('select 1');

我通常导入它并定义一个别名:

use Illuminate'Database'Capsule'Manager as DB;
// ...
$select = DB::select('select 1');

此外,如果您需要进行原始查询,那么在bootEloquent()之后调用setAsGlobal()可能会有所帮助,比如这个

$capsule->addConnection($sqliteDb);
$capsule->bootEloquent();
$capsule->setAsGlobal();   // <--- this

在Slim 4中,我们可以使用$this->getConnection()->select($sql);

 <?php
namespace App'Models;
use Illuminate'Database'Eloquent'Model;

class Product extends Model{
    protected $table = 'products';
    public $timestamps = false;
    protected $fillable = ["name", "price", "quantity", "supplier", "image", "category"];
    public function getProductsByCategory(){
        $sql = 'SELECT p.id,
                        p.name,
                        p.price,
                        p.quantity,
                        p.supplier,
                        p.image,
                        p.category,
                (SELECT IF(COUNT(*) >= 1, TRUE, FALSE) FROM favorite f WHERE f.user_id = 1 AND f.product_id = p.id) AS isFavourite,
                (SELECT IF(COUNT(*) >= 1, TRUE, FALSE) FROM carts c WHERE c.user_id = 1 AND c.product_id = p.id) AS isInCart
                FROM products p';
        return $this->getConnection()->select($sql);
    }   
}